import { onMessage } from 'webext-bridge/content-script';
import { EVENT_SHOPEE_PRODUCT_SELECT_VARIANT } from '@/bridge/config/event';
import { listenerFetch } from '@content/service/event';
import { onChangeTab, onLocationChange } from '@content/service/util';
import { ProductDetailLoader } from './product/detail';
import { ProductSearchLoader } from './product/search';
import { ShopSpyBtnLoader } from './shop/spyBtn';
import { tableProductStyle, affIframe, btnImageDownloader } from './service';
import { loggerContent } from '@/plugins/logger';

const productSearchLoader = new ProductSearchLoader();
const productDetailLoader = new ProductDetailLoader();
const shopSpyBtnLoader = new ShopSpyBtnLoader();

onMessage(EVENT_SHOPEE_PRODUCT_SELECT_VARIANT, async ({ data }) => {
  productDetailLoader.clickSelectVariant(data).catch((error) => {
    loggerContent.error({
      msg: 'CLICK_SELECT_VARIANT_ERROR',
      error,
    });
  });
});

const loaderContent = async () => {
  productSearchLoader.initialize().catch(() => {});
  productDetailLoader.initialize().catch(() => {});
  shopSpyBtnLoader.initialize().catch(() => {});
  tableProductStyle().catch(() => {});
  affIframe().catch(() => {});
};

export function main(ctx) {
  document.addEventListener('readystatechange', () => {
    tableProductStyle().catch(() => {});
  });

  ctx.addEventListener(window, 'scroll', async () => {
    productSearchLoader.initialize().catch(() => {});
  });

  loaderContent();

  ctx.setTimeout(() => {
    loaderContent();
  }, 3000);

  onChangeTab(() => {
    ctx.setTimeout(() => {
      loaderContent();
    }, 1000);
  });

  onLocationChange(() => {
    ctx.setTimeout(() => {
      loaderContent();
    }, 500);
    shopSpyBtnLoader.initialize().catch(() => {});
  });

  ctx.setInterval(() => {
    btnImageDownloader().catch(() => {});
  }, 500);

  ctx.setTimeout(() => {
    listenerFetch();
  }, 500);
}
