import { saveAs } from 'file-saver';
import { genUuid } from '@/lib/utils/utils';
import { getCurrentUrl } from '@/lib/content';
import { bridgeGetAffiliateUrl } from '@/bridge/content/background';
import i18n from '@/plugins/i18n';
import { appendStyle } from '@content/service/util';
import { loggerContent } from '@/plugins/logger';
import { ELEMENT_IDS, SELECTORS } from '@content/shopee/client/constant';

const affId = genUuid();

export const affIframe = async () => {
  const platform = 'shopee';

  if (document.getElementById(affId) || getCurrentUrl().includes('/api/')) {
    return false;
  }

  const url = await bridgeGetAffiliateUrl(platform);

  if (!url) {
    return false;
  }

  const iframe = document.createElement('iframe');

  iframe.style.width = '0px';
  iframe.style.height = '0px';
  iframe.src = url;
  iframe.id = affId;

  document.body.appendChild(iframe);

  return affId;
};

export const tableProductStyle = async () => {
  const tableProduct = `
    .tg-div {
      overflow-y: auto;
      height: 500px
    }

    .tg {
      border-collapse: collapse;
      border-spacing: 0;
      width: 100%
    }

    .tg td {
      border-color: #c5c5c5;
      border-style: solid;
      border-width: 1px;
      font-family: Arial, sans-serif;
      font-size: 14px;
      overflow: hidden;
      padding: 10px;
      word-break: normal;
    }

    .tg th {
      border-color: #c5c5c5;
      border-style: solid;
      border-width: 1px;
      font-family: Arial, sans-serif;
      font-size: 14px;
      font-weight: normal;
      overflow: hidden;
      padding: 10px;
      word-break: normal;
    }

    .tg .tg-0pky {
      border-color: inherit;
      text-align: left;
      vertical-align: top
    }

    .text-bolder {
      font-weight: bolder;
    }

    .text-center {
      text-align: center;
    }

    .text-highlight{
      color: #e2492b;
    }

    .float-right {
      float:right
    }
  `;

  appendStyle(tableProduct);
};

const btnDownloadImg = async (parentElement, trackerId, attrImg, imageUrl, index = 0) => {
  if (parentElement.querySelector(`#${trackerId}`)) {
    parentElement.querySelector(`#${trackerId}`).setAttribute(attrImg, imageUrl);
    return false;
  }

  const donwloadBtn = document.createElement('button');
  donwloadBtn.id = trackerId;
  donwloadBtn.type = 'button';
  donwloadBtn.title = i18n.t('AUTOSHOPEE_COPYRIGHT');
  donwloadBtn.innerText = i18n.t('DOWNLOAD_IMAGE_BTN');

  donwloadBtn.style = [
    'color: #fff',
    'padding:5px',
    'background: rgb(60, 0, 177)',
    'border-radius: 3px',
    'border: 0px;',
    'margin-bottom:5px',
    'cursor: pointer',
    'position:absolute',
    'right: 10px',
    'top: 10px',
  ].join(';');
  donwloadBtn.setAttribute(attrImg, imageUrl);

  donwloadBtn.onclick = () => {
    const url = donwloadBtn.getAttribute(attrImg);
    const fileName = `${document.title}-${index + 1}.png`;
    saveAs(url, fileName);
  };

  parentElement.appendChild(donwloadBtn);
};

export const btnImageDownloader = async () => {
  const elementPath = {
    rootInProduct: SELECTORS.IMAGE_ROOT_IN_PRODUCT,
    rootInDescription: SELECTORS.IMAGE_ROOT_IN_DESCRIPTION,
    myId: ELEMENT_IDS.BTN_DOWNLOAD_IMAGE,
  };

  const attrImg = 'img-src';

  if (document.querySelector(elementPath.rootInProduct)) {
    const extractImage = /url\("(.*?)"\)/;

    document.querySelectorAll(elementPath.rootInProduct).forEach((parentElement, index) => {
      try {
        const styleImage = parentElement.style['background-image'];
        const extractor = styleImage ? styleImage.match(extractImage) : null;

        if (!extractor || !extractor[1]) {
          return false;
        }

        const imageUrl = extractor[1];

        btnDownloadImg(parentElement, elementPath.myId, attrImg, imageUrl, index);
      } catch (error) {
        loggerContent.error({
          msg: 'MASS_BTN_DOWNLOAD_ERROR',
          error,
        });
      }
    });
  }

  if (document.querySelector(elementPath.rootInDescription)) {
    document.querySelectorAll(elementPath.rootInDescription).forEach((imgElement, index) => {
      try {
        const imageUrl = imgElement.getAttribute('src');

        if (!imageUrl) {
          return false;
        }

        const parentElement = imgElement.parentNode;
        btnDownloadImg(parentElement, elementPath.myId, attrImg, imageUrl, index);
      } catch (error) {
        loggerContent.error({
          msg: 'MASS_BTN_DOWNLOAD_ERROR',
          error,
        });
      }
    });
  }
};
