let globalLogger;

class EventLogger {
 appId = '';
 deviceInfo = {};
 version = 10
 deviceStr = '';
 events = [];
 info = {}; //用户信息


 constructor({ appId, deviceInfo, info }) {
  this.appId = appId;
  let u = navigator.userAgent;
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  let tzOffset = new Date().valueOf();
  this.deviceInfo = {
    platform: isAndroid ? 'ANDROID' : 'IOS',
    country: navigator.languages[1],
    tzOffset,
    deviceType: 'other',
    brand: '',
    model: '',
    screenH: document.body.clientHeight,
    screenW: document.body.clientWidth,
    osVersion: '',
    language: navigator.language,
    ...deviceInfo
  };
  for (let key in this.deviceInfo) this.deviceStr += `${key}=${this.deviceInfo[key]};`;
  this.info = info;
 }


 getHeaders() {
  let headers = new Headers();
  headers.append('X-APP-ID', this.appId);
  headers.append('X-DEVICE-INFO', this.deviceStr)
  headers.append('content-type', 'application/json');
  headers.append('Content-Encoding', 'gzip');
  return headers;
 }

 zip(str) {
  const binaryString = pako.gzip(str)
  return binaryString;
 }

 log(event) {
  event = {
   ...event,
   timestamp: Date.now(),
   info: this.info
  };
  this.events.push(event);
  if (this.events.length > 0) this.logEvent();
 }


 async logEvent() {
  const requestBody = {
   version: this.version,
   deviceInfo: this.deviceInfo,
   events: [...this.events]
  };
  const bodyStr = JSON.stringify(requestBody);
  const gzippedStr = this.zip(bodyStr);
  const config = {
   headers: this.getHeaders(),
   body: gzippedStr,
   method: 'POST',
  };
  await fetch('https://collect.saas.castbox.fm/event', config);
  this.events = [];
 }
}

/**
 * 
 * appInfo {
 *  appId
 *  deviceInfo
 *  version,
 *  info
 * }
 */
function initEventLogger(appInfo) {  
 globalLogger = new EventLogger(JSON.parse(appInfo));
}

function castboxLogEvent(eventName, param, properties) {
 if (globalLogger) {
  globalLogger.log({
   event: eventName,
   param: JSON.parse(param),
   properties: JSON.parse(properties)
  });
 }
}


