import puppeteer from 'puppeteer';
import {
  SEARCH_URL,
  NAVIGATION_TIMEOUT,
  TEMP_DIR,
  SITE_COOKIES,
} from '../util/Constants';
import Selectors, { SUBMIT_FORM_ID } from '../util/Selectors';
import { createCacheDirectories } from '../util/TempDirCreator';

const getPuppeteerOptions = () => {
  const options = {};
  if (process.env.NODE_ENV === 'production') {
    options.args = ['--no-sandbox'];
  }
  return options;
};
console.log(Selectors);
class CookieMonster {
  cache;
  browser;
  page;

  constructor(cache) {
    this.cache = cache;
    createCacheDirectories(TEMP_DIR.screenshots);
  }

  async submitForm(plate) {
    await this.page.focus(Selectors.form.plate);
    await this.page.keyboard.type(plate);
    const path = {
      s: `j_idt${SUBMIT_FORM_ID}:j_idt137`,
      u: `j_idt${SUBMIT_FORM_ID}`,
    };
    await this.page.evaluate(() => {
      // eslint-disable-next-line no-undef
      PrimeFaces.ab({
        s: 'j_idt110:j_idt137',
        u: 'j_idt110',
      });
    });
    await this.page.waitForNavigation({
      timeout: NAVIGATION_TIMEOUT,
      waitUntil: 'domcontentloaded',
    });
  }

  async launchPage() {
    this.browser = await puppeteer.launch(getPuppeteerOptions());
    this.page = await this.browser.newPage();
    await this.page.goto(SEARCH_URL);
    await this.page.setCookie(...SITE_COOKIES);
  }

  async cleanup(plate) {
    await this.page.screenshot({
      path: `${TEMP_DIR.screenshots}/${plate}.png`,
      fullPage: true,
    });
    await this.browser.close();
  }

  async init(plate) {
    try {
      console.log(`Fetching data for ${plate}`);
      await this.launchPage();
      try {
        await this.submitForm(plate);
      } catch (e) {
        console.warn(`Got a timeout for ${plate} but data might still be there, sometimes takes longer to load entire page.`, e.message);
      }
      const pageContent = await this.page
        .$eval(Selectors.container.main, (element) => element.innerHTML);
      await this.cleanup(plate);
      console.log(`Successfully fetched fresh data for ${plate}`);
      return pageContent;
    } catch (e) {
      await this.cleanup(plate);
      throw e;
    }
  }
}

export default CookieMonster;
