import uuid from './uuid';
import { hex_md5 } from './md5';
import { currentTimeMs } from './timeutil';

function getOrDefault(realValue, defaultValue) {
  if (realValue === 'undefined') {
    return defaultValue;
  } else {
    return realValue || defaultValue;
  }
}

/**
 * 对象驼峰命名转下划线命名
 * @param {} obj
 * @returns
 */
function mapCamel2UnderlineObj(obj) {
  if (obj) {
    let newObj = {};
    Object.keys(obj).forEach((key) => {
      let newKey = key.replace(/([A-Z])/g, '_$1').toLowerCase();
      newObj[newKey] = obj[key];
    });
    return newObj;
  }
  return obj;
}

function generateParams(user_msg, devices, vic, adspaceInfo) {
  let timstamp = currentTimeMs();
  let reqid = uuid();
  let sign = hex_md5(`${reqid}_${timstamp}_${user_msg.token}`);
  console.log(user_msg);
  return {
    sign: sign,
    ts: timstamp,
    mid_id: user_msg.mid_id,
    req_id: reqid,
    version: 'v1.0',
    adspace: {
      adspace_id: adspaceInfo.adspace_id,
      play_time: 0,
      support_dl: false,
      width: adspaceInfo.width,
      height: adspaceInfo.height,
      play_time: adspaceInfo.maxDuration || 15,
      min_cpm: adspaceInfo.minCpm,
      adlen: adspaceInfo.maxAdCount,
    },
    device: devices,
    user: {
      uuid: user_msg.userId || '',
      area_code: user_msg.area_code,
      common_code: user_msg.common_code,
      vip: user_msg.vip,
    },
    vic: mapCamel2UnderlineObj(vic) || {},
  };
}

function generateInitParams(user_msg, devices) {
  return {
    ts: currentTimeMs(),
    mid_id: user_msg.mid_id,
    req_id: uuid(),
    version: 'v1.0',
    device: devices,
    user: {
      uuid: user_msg.userId || '',
      area_code: user_msg.area_code,
      vip: user_msg.vip,
    },
  };
}

function concatCdnInitParams(agent, device, userParams) {
  return {
    h: agent, //访问接口（hostname）
    mf: device.brand, //	厂家
    mod: device.model, //硬件型号
    v: device.app_version, //客户端版本号,如YYS.6.4.0.Y3.6.HNYDIPTV.0.0_Release
    did: device.android_id, //移动设备id
    ch: userParams.mid_id, //联盟mid
    m: device.mac, //mac地址	网卡或wifi MAC地址
  };
}

function concatErrorInitParams(device, userParams, adspace) {
  return {
    adid: device.android_id,
    appver: device.app_version, //
    cc: userParams.common_code, //城市地区id	根据用户ip转化来，用于地域定向
    cxid: userParams.mid_id, //流量渠道id
    mac: device.mac, //硬件mac地址	硬件mac地址
    mn: device.model, //设备型号
    did: device.imei,
    ch: userParams.mid_id,
    brand: device.brand,
    ssp_aid: adspace.adspace_id,
  };
}

export {
  generateParams,
  generateInitParams,
  getOrDefault,
  concatCdnInitParams,
  concatErrorInitParams,
};
