import getUserToken from '../utils/getUserToken.js';
import log from '../utils/log.js';

export default async function (request) {
  log.info('handling findUrlDescriptor');

  if (await isBlacklisted(request.url)) {
    log.info(`url ${request.url} is blacklisted`);
    return null;
  }

  let userToken = await getUserToken();
  return await fetch('https://next-page-server.ciborski.com/', { // 'https://next-page-server.ciborski.com/' 'http://127.0.0.1:8787/'
    method: 'post',
    body: request.url,
    headers: {
      'X-BrowserInfo': JSON.stringify(request.browserInfo),
      'Authorization': `Bearer ${userToken}`,
      'Version': '2.0.0',
    },
  }).then(async response => {
    const text = await response.text();
    log.info(`response.text()`, text);
    let resultsArray = JSON.parse(text);
    return await matchLocal(request.url, (rlz) => {
      resultsArray = resultsArray.concat(rlz);
      return resultsArray;
    });
  }).catch(error => {
    log.info(error);
    return null;
  })
}

async function matchLocal(urlToMatch, callback) {
  let { rules } = await chrome.storage.sync.get(["rules"]);
  if (!rules) {
    rules = '';
  }

  let rlz = [];

  let arr = rules.split('\n').map(s => s.trim());
  for (let i = 0; i < arr.length; i += 4) {
    let url = skipFirstWord(arr[i + 0]);
    let pageElement = skipFirstWord(arr[i + 1]);
    let nextLink = skipFirstWord(arr[i + 2]);
    let emptyLine = arr[i + 3];

    let rx = new RegExp(url);
    if (rx.test(urlToMatch)) {
      rlz.push({
        url,
        pageElement,
        nextLink,
      })
    }
  }
  return callback(rlz);
}

async function isBlacklisted(url) {
  let { blacklist } = await chrome.storage.sync.get(['blacklist']);
  if (!blacklist) {
    blacklist = '';
  }

  let urlRegExps = blacklist.split('\n').map(s => s.trim()).filter(Boolean);

  for (let i = 0; i < urlRegExps.length; i++) {
    let regexp = new RegExp(urlRegExps[i]);
    log.info(`testing "${url}" against "${urlRegExps[i]}"`);
    let isMatch = regexp.test(url);
    if (isMatch) {
      return true;
    }
  }

  return false;
}




function skipFirstWord(str) {
  if (!str) {
    return str;
  }

  let idx = str.indexOf(' ');
  return str.substring(idx + 1);
}