/* eslint-disable no-undef, no-underscore-dangle */
// Instrumentation pings and dynamic pc logic
const browserDefaultsUrl = 'https://browserdefaults.microsoft.com/';
const extensionId = chrome.runtime.id;
const manifest = chrome.runtime.getManifest();
const extensionVersion = manifest.version;
const versionName = manifest.version_name;

let defaultpc = 'WOWT00';
if (versionName) {
  const versionStrs = versionName.split('-');
  if (versionStrs.length > 1) {
    // eslint-disable-next-line prefer-destructuring
    defaultpc = versionStrs[1];
  }
}

const PING_ALARM = 'PINGALARM';

/* Function to create an unique machine id */
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  let MachineGUID = s4() + s4() + s4() + s4() + s4() + s4() + s4() + s4();
  MachineGUID = MachineGUID.toLocaleUpperCase();
  chrome.storage.local.set({ machineId: MachineGUID });
  return MachineGUID;
}

function getBrowserDefaultDetails(channelId) {
  return new Promise((resolve) => {
    // Fetching Machine Id, Partner Code, DPC and channel details from browserdefaults.microsoft.com
    chrome.cookies.get({ url: browserDefaultsUrl, name: chrome.runtime.id }, (cookie) => {
      const details = {
        machineId: guid(),
        pc: '',
        channel: channelId || 'organic',
        bmkt: '',
        _dpc: '',
      };
      if (cookie) {
        const cookieValue = String(cookie.value).split('&');
        for (let i = 0; i < cookieValue.length; i += 1) {
          const cookieData = cookieValue[i].split('=');
          const [key, value] = cookieData;
          if (key.toLocaleUpperCase() === 'MI') {
            details.machineId = value;
          } else if (key.toLocaleUpperCase() === 'CH') {
            details.channel = value;
          } else if (key.toLocaleUpperCase() === 'PC') {
            details.pc = value;
          } else if (key.toLocaleUpperCase() === 'BM') {
            details.bmkt = value;
          }
        }
        chrome.cookies.remove({ url: browserDefaultsUrl, name: chrome.runtime.id });
      }

      // Assign PC values
      if (!details.pc) {
        details.pc = defaultpc;
      }
      // Assign Browser Market
      if (details.bmkt === '') {
        details.bmkt = navigator.language;
      }
      // Assign DPC
      if (details.pc !== defaultpc) {
        details._dpc = `${details.pc}_${details.channel}`;
      } else {
        details._dpc = details.channel;
      }
      // store in chrome storage
      chrome.storage.local.set(details, () => { resolve(details); });
    });
  });
}

function SendPingDetails(status, bmkt, pc, channel, dpc, machineId) {
  const manifestData = chrome.runtime.getManifest();
  const startIndex = navigator.userAgent.indexOf('(');
  const endIndex = navigator.userAgent.indexOf(')');
  const OS = navigator.userAgent.substring(startIndex + 1, endIndex).replace(/\s/g, '');
  const browserLanguage = bmkt || navigator.language;
  const eventId = '37';

  const extensionName = manifestData.name.replace(/ /g, '').replace('&', 'and');

  let browserVersion;
  if (navigator.userAgent.indexOf('Edg') !== -1) {
    browserVersion = navigator.userAgent.substr(navigator.userAgent.indexOf('Edg')).split(' ')[0].replace('/', '');
  } else {
    browserVersion = navigator.userAgent.substr(navigator.userAgent.indexOf('Chrome')).split(' ')[0].replace('/', '');
  }

  // eslint-disable-next-line @typescript-eslint/naming-convention
  const _pc = pc || defaultpc;
  let pingURL = 'https://go.microsoft.com/fwlink/?linkid=2243942&';
  let tVData = `TV=is${_pc}|pk${extensionName}|tm${browserLanguage}|bv${browserVersion}|ex${extensionId}|es${status}`;
  if (channel) {
    tVData = `${tVData}|ch${channel}`;
  }
  if (dpc) {
    tVData = `${tVData}|dp${dpc}`;
  }
  let UD = `MI=${machineId}&LV=${extensionVersion}&OS=${OS}&TE=${eventId}&${tVData}`;
  UD = btoa(encodeURI(UD));
  pingURL = `${pingURL}UD=${UD}&ver=2`;
  pingURL = encodeURI(pingURL);
  fetch(pingURL);
}

chrome.runtime.onInstalled.addListener(({ reason }) => {
  if (reason === 'install') {
    console.log('Inside install');
    getBrowserDefaultDetails()
      .then((details) => {
        chrome.storage.local.set({ ExtnVersion: extensionVersion });

        // Call for install Ping
        SendPingDetails('1', details.bmkt, details.pc, details.channel, details._dpc, details.machineId);
        chrome.alarms.create(PING_ALARM, {
          delayInMinutes: 1,
          periodInMinutes: 1440,
        });
      });
  } else if (reason === 'update') {
    console.log('update');
    chrome.storage.local.set({ ExtnVersion: extensionVersion });

    // Call for Update Ping
    chrome.storage.local.get(['pc', 'bmkt', 'machineId', '_dpc', 'channel'], (items) => {
      console.log('Update Ping');
      SendPingDetails('3', items.bmkt, items.pc, items.channel, items._dpc, items.machineId);
    });
  }
});

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === PING_ALARM) {
    chrome.storage.local.get(['pc', 'bmkt', 'machineId', '_dpc', 'channel'], (items) => {
      SendPingDetails('2', items.bmkt, items.pc, items.channel, items._dpc, items.machineId);
    });
  }
});
