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 { BulkDownloadLoader } from './product/bulkDownload';
import { ShopSpyBtnLoader } from './shop/spyBtn';
import { tableProductStyle, affIframe, btnImageDownloader } from './service';
import { loggerContent } from '@/plugins/logger';
import { CONTENT_OPTIONS } from './constant';

let productSearchLoader;
const productDetailLoader = new ProductDetailLoader();
let shopSpyBtnLoader;
let bulkDownloadLoader;

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

const loaderContent = async () => {
  if (CONTENT_OPTIONS.spySearchBtn) {
    productSearchLoader.initialize().catch(() => {});
  }
  if (CONTENT_OPTIONS.spyProductDetail) {
    productDetailLoader.initialize().catch(() => {});
  }
  if (CONTENT_OPTIONS.spyShopBtn) {
    try {
      shopSpyBtnLoader.initialize();
    } catch (error) {
      loggerContent.error({
        msg: 'SHOP_SPY_INIT_ERROR',
        error,
      });
    }
  }

  if (CONTENT_OPTIONS.bulkDownload) {
    bulkDownloadLoader.initialize();
  }

  tableProductStyle().catch(() => {});
  affIframe().catch(() => {});
};

export function main(ctx) {
  productSearchLoader = new ProductSearchLoader(ctx);
  shopSpyBtnLoader = new ShopSpyBtnLoader(ctx);
  bulkDownloadLoader = new BulkDownloadLoader(ctx);

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

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

  loaderContent();

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

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

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

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

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