import queryString from 'query-string';
import delay from 'delay';
import {
  browseTabCreate, browseTabQuery, browseTabReload, browseTabSendMessage, browseTabOnUpdate, browseTabRemove, browseTabGet,
} from './api';

export const createPopupUrl = (path = '', qs = {}) => {
  const index = 'popup.html';
  return [index, '#', path || '/', qs ? '?' : '', qs ? queryString.stringify(qs) : ''].filter((item) => item).join('');
};

export const openPopupUrl = (path = '', qs = {}) => {
  const url = createPopupUrl(path, qs);

  browseTabCreate({
    url,
    active: true,
  });
};

export const openExternalUrl = (url, active = true) => {
  browseTabCreate({
    url,
    active,
  });
};

export const reloadTabId = (tabId, bypassCache = false) => {
  return browseTabReload(tabId, {
    bypassCache,
  });
};

export const closeTabId = (tabId) => {
  return browseTabRemove(tabId);
};

/**
 *
 * @param {string} url
 * @param {number} sleep
 * @returns {Promise<BrowserTabStore>}
 */
export const openAndCloselUrl = async (url, sleep = 1000) => {
  const tab = await browseTabCreate({
    url,
    active: false,
  });

  await delay(sleep);

  closeTabId(tab.id);

  return tab;
};

/**
 *
 * @returns {Promise<BrowserTabStore>}
 */
export const getTabCurrent = async () => {
  const listTab = await browseTabQuery({
    active: true,
  });

  return listTab[0];
};

/**
 *
 * @returns {Promise<BrowserTabStore>}
 */
export const getTabLastest = async () => {
  const listTab = await browseTabQuery({
    active: true,
    lastFocusedWindow: true,
  });

  if (!(listTab && listTab.length)) {
    return null;
  }
  return listTab[0];
};

/**
 *
 * @returns {Promise<BrowserTabStore[]>}
 */
export const getAllTab = async () => {
  return browseTabQuery({});
};

export const getCurrentUrl = async () => {
  const listTab = await browseTabQuery({
    active: true,
    lastFocusedWindow: true,
  });

  if (!(listTab && listTab.length)) {
    return '';
  }

  return listTab[0].url;
};

export const reloadTabCurrent = async (bypassCache = false) => {
  const tab = await getTabLastest();

  reloadTabId(tab.id, bypassCache);
};

export const sendMessageTabId = async (
  tabId,
  payload = {
    _id: {},
    event: '',
    data: {},
  },
) => {
  return new Promise((resolve) => {
    browseTabSendMessage(tabId, payload, (response) => {
      if (chrome.runtime.lastError) {
        resolve(null);
        return;
      }
      resolve(response);
    });
  });
};

export const tabOnUpdate = (callback) => {
  browseTabOnUpdate.addListener(callback);
};

export const getTabId = async (tabId) => {
  return browseTabGet(tabId);
};

export const queryTabId = async (tabId) => {
  const listTab = await getAllTab();
  return listTab.find((tab) => tab.id === tabId);
};
