// See the Electron documentation for details on how to use preload scripts:
// https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts
import { contextBridge } from 'electron';
import HeadlessController from './modules/HeadlessController/controller';
import Recorder from './modules/recorder';
import Tracker from './modules/tracker';
import Loader from './modules/loader';
import { EVENT_NAMES } from './constants/define';
import Overlay from './modules/overlay-controller';
import Store from './modules/store';
import HightLight from './modules/highlight';
import ContextMenu from './modules/context-menu';
import { HIGHTLIGHT_TYPES } from './modules/highlight/constants';
import { findLast, isEmpty, last } from 'lodash';

const { PAUSE, RESUME } = EVENT_NAMES.CLIENT_RECORDER;

contextBridge.exposeInMainWorld('headlessRecorder', {
  // record user interaction from target website
  record: async ({ options, onUpdateEvents }) => {
    const store = new Store({
      options,
      onUpdateEvents,
    });
    contextBridge.exposeInMainWorld('headlessRecorderAPI', {
      [PAUSE]: () => store.pause(),
      [RESUME]: () => store.resume(),
      toggleTableMode: () => store.toggleTableMode(),
    });

    const headlessRecorder = new HeadlessController({
      loader: new Loader({ store }),
      recorder: new Recorder({ store }),
      tracker: new Tracker({ store }),
      overlay: new Overlay({ store }),
      hightlight: new HightLight({ store }),
      contextMenu: new ContextMenu({ store }),
      store,
    });
    headlessRecorder.init();
  },
  // this function is used to reselect selector
  // when user wanna edit the extracted data step
  reselectSelector: ({ eventLogs, stepId, onUpdateSelector }) => {
    try {
      const lastExtractedData = findLast(eventLogs, (eventLog) => eventLog.action === 'extract-data');

      const store = new Store({
        options: {
          isTableMode: lastExtractedData?.isTable,
        },
        eventLogs,
        onUpdateSelector,
        eventId: stepId,
      });

      contextBridge.exposeInMainWorld('headlessRecorderAPI', {
        [PAUSE]: () => store.pause(),
        [RESUME]: () => store.resume(),
        toggleTableMode: () => store.toggleTableMode(),
      });

      const headlessRecorder = new HeadlessController({
        recorder: new Recorder({ store }),
        tracker: new Tracker({ store }),
        overlay: new Overlay({ store }),
        hightlight: new HightLight({ store }),
        contextMenu: new ContextMenu({ store }),
        store,
      });
      headlessRecorder.init();

      let eventLog;
      if (eventLogs.length > 0) {
        eventLog = eventLogs.find((eventLog) => eventLog.id === stepId);
      }

      if (eventLog) {
        if (eventLog.isTable) {
          if (!isEmpty(eventLog.selector))
            store.addHighlightingSelector(HIGHTLIGHT_TYPES.EXTRACT_TABLE, eventLog.selector);
          if (!isEmpty(eventLog.paginationSelector))
            store.addHighlightingSelector(HIGHTLIGHT_TYPES.EXTRACT_PAGINATION, eventLog.paginationSelector);
          if (!isEmpty(eventLog.nextPageSelector))
            store.addHighlightingSelector(HIGHTLIGHT_TYPES.EXTRACT_NEXT_PAGE, eventLog.nextPageSelector);
        } else {
          if (!isEmpty(eventLog.selectedFields)) {
            eventLog.selectedFields?.map((field) => {
              store.addHighlightingSelector(HIGHTLIGHT_TYPES.EXTRACT_FIELD, field?.selector, field?.name);
            });
          }
        }
      }
    } catch (error) {
      console.log(JSON.stringify(error));
      console.log('there is an error occured', error);
    }
  },
  recordDetailColumn: async ({ onUpdateRecordScrapingDetailColumn }) => {
    try {
      localStorage.clear();
      const store = new Store({
        options: {
          isTableMode: false,
        },
        onUpdateRecordScrapingDetailColumn,
      });

      const headlessRecorder = new HeadlessController({
        recorder: new Recorder({ store }),
        tracker: new Tracker({ store }),
        hightlight: new HightLight({ store }),
        contextMenu: new ContextMenu({ store }),
        store,
      });
      headlessRecorder.init();
    } catch (error) {
      console.log('there is an error occured', error);
    }
  },
  initLoader: () => {
    const loader = new Loader();
    loader.init();
  },
  initialHighlight: (eventLog) => {
    const store = new Store();
    // const hightlight = new HightLight({ store });
    // hightlight.init();
    const headlessRecorder = new HeadlessController({
      loader: new Loader({ store }),
      hightlight: new HightLight({ store }),
      store,
    });

    headlessRecorder.init();
    if (eventLog) {
      if (eventLog.isTable) {
        if (!isEmpty(eventLog.selector))
          store.addHighlightingSelector(HIGHTLIGHT_TYPES.EXTRACT_TABLE, eventLog.selector);
        if (!isEmpty(eventLog.paginationSelector))
          store.addHighlightingSelector(HIGHTLIGHT_TYPES.EXTRACT_PAGINATION, eventLog.paginationSelector);
        if (!isEmpty(eventLog.nextPageSelector))
          store.addHighlightingSelector(HIGHTLIGHT_TYPES.EXTRACT_NEXT_PAGE, eventLog.nextPageSelector);
      } else {
        if (!isEmpty(eventLog.selectedFields)) {
          eventLog.selectedFields?.map((field) => {
            store.addHighlightingSelector(HIGHTLIGHT_TYPES.EXTRACT_FIELD, field?.selector);
          });
        }
      }
    }
  },
});

// contextBridge.exposeInMainWorld('headlessRecorderAPI', {
//   [PAUSE]: () => window.postMessage({ control: PAUSE }, '*'),
//   [RESUME]: () => window.postMessage({ control: RESUME }, '*'),
// });
