/**
 利用chrome的fetch来避免跨域
 **/
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type == 'api') {
    new Promise((resolve) => {
      let headers = {};
      if (request.needMallId) {
        headers.Mallid = request.mallId;
      }
      if (request.anti) {
        headers["Anti-Content"] = request.anti
      }
      headers['Content-Type'] = 'application/json';
      headers.cookie = getCookie();
      Promise.resolve().then(() => fetch(request.url, {
        'headers': headers,
        'method': 'POST',
        'referrerPolicy': 'no-referrer',
        'credentials': 'include',
        'body': JSON.stringify(request.data),
        'mode': 'cors'
      })).then((res) => {
        resolve(res.json());
      });
    }).then(sendResponse);
  } else if (request.type == 'temuApi') {
    new Promise((resolve) => {
      let headers = {};
      if (request.anti) {
        headers["Anti-Content"] = request.anti
      }
      headers['Content-Type'] = 'application/json';
      headers.cookie = getTemuCookie();
      Promise.resolve().then(() => fetch(request.url, {
        'headers': headers,
        'method': 'POST',
        'referrerPolicy': 'no-referrer',
        'credentials': 'include',
        'body': JSON.stringify(request.data),
        'mode': 'cors'
      })).then((res) => {
        resolve(res.json());
      });
    }).then(sendResponse);
  } else if (request.type == 'temu') {
    new Promise((resolve) => {
      let headers = {};
      headers['Content-Type'] = 'text/html';
      headers.cookie = getTemuCookie();
      Promise.resolve().then(() => fetch(request.url, {
        'headers': headers,
        'method': 'GET',
        'referrerPolicy': 'no-referrer',
        'credentials': 'include',
        'mode': 'cors'
      })).then((res) => {
        // 创建了一个数据读取器
        const reader = res.body.getReader();
        // 创建了一个文本解码器
        const decoder = new TextDecoder();

        let text = ""
        reader.read().then(function processText({ done, value }) {
          // Result 对象包含了两个属性：
          // done  - 当 stream 传完所有数据时则变成 true
          // value - 数据片段。当 done 为 true 时始终为 undefined
          if (done) {
            resolve(text);
            return;
          }
          // 将字节流转换为字符
          text = text + decoder.decode(value)
          // 再次调用这个函数以读取更多数据
          return reader.read().then(processText);
        });
      });
    }).then(sendResponse);
  } else if (request.type == 'aliexpress') {
    new Promise((resolve) => {
      let headers = {};
      headers['Content-Type'] = 'text/html';
      headers.cookie = getAliexpressCookie();
      Promise.resolve().then(() => fetch(request.url, {
        'headers': headers,
        'method': 'GET',
        'referrerPolicy': 'no-referrer',
        'credentials': 'include',
        'mode': 'cors'
      })).then((res) => {
        // 创建了一个数据读取器
        const reader = res.body.getReader();
        // 创建了一个文本解码器
        const decoder = new TextDecoder();

        let text = ""
        reader.read().then(function processText({ done, value }) {
          // Result 对象包含了两个属性：
          // done  - 当 stream 传完所有数据时则变成 true
          // value - 数据片段。当 done 为 true 时始终为 undefined
          if (done) {
            resolve(text);
            return;
          }
          // 将字节流转换为字符
          text = text + decoder.decode(value)
          // 再次调用这个函数以读取更多数据
          return reader.read().then(processText);
        });
      });
    }).then(sendResponse);
  } else if (request.type == 'notify') {
    chrome.notifications.create(
        "" + Math.random(), {
          type: "basic",
          title: "TEMU助手",
          message: "您店铺【" + request.mallName + "】的商品【" + request.productName + "】成功加入发货台，请尽快处理",
          iconUrl: "./icons/48.png"
        }, null
    )
  }

  return true;
});

chrome.action.onClicked.addListener(function () {
  chrome.tabs.create({
    url: "./popup.html"
  }, function (tab) {
    console.log('tab is:' + tab);
  });
});

chrome.webRequest.onSendHeaders.addListener(details => {
  if (details.url && (details.url.indexOf('joinDeliveryGoodsOrderPlatform')  != -1)) {
    details.requestHeaders.push({
      name: 'Referer',
      value: 'https://kuajing.pinduoduo.com/main/order-manage'
    })
    for (let i = 0 ; i < details.requestHeaders.length; i++) {
      if (details.requestHeaders[i].name == 'Origin') {
        details.requestHeaders[i].value = 'https://kuajing.pinduoduo.com'
        break;
      }
    }
  } else if (details.url && (details.url.indexOf('mms/userInfo')  != -1)) {
    details.requestHeaders.push({
      name: 'Referer',
      value: 'https://kuajing.pinduoduo.com/main/order-manage'
    })
    for (let i = 0 ; i < details.requestHeaders.length; i++) {
      if (details.requestHeaders[i].name == 'Origin') {
        details.requestHeaders[i].value = 'https://kuajing.pinduoduo.com'
        break;
      }
    }
  }
},
{urls: ["<all_urls>"]},["requestHeaders", "extraHeaders"]);


function getCookie() {
  const url = new URL("https://kuajing.pinduoduo.com/");
  let cStr = '';
  chrome.cookies.getAll({domain: url.host}, (cookie) => {
    cookie.map((c) => {
      cStr += c.name + '=' + c.value + ';';
    });
  });
  return cStr;
}

function getTemuCookie() {
  const url = new URL("https://www.temu.com/");
  let cStr = '';
  chrome.cookies.getAll({domain: url.host}, (cookie) => {
    cookie.map((c) => {
      cStr += c.name + '=' + c.value + ';';
    });
  });
  return cStr;
}

function getAliexpressCookie() {
  const url = new URL("https://www.aliexpress.us/");
  let cStr = '';
  chrome.cookies.getAll({domain: url.host}, (cookie) => {
    cookie.map((c) => {
      cStr += c.name + '=' + c.value + ';';
    });
  });
  return cStr;
}