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

const getPuppeteerOptions = () => {
  const options = {};
  if (process.env.NODE_ENV === 'production') {
    options.args = ['--no-sandbox'];
  }
  return options;
};

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);
    await this.page.evaluate(() => {
      // eslint-disable-next-line no-undef
      PrimeFaces.ab({
        s: 'j_idt104:j_idt131',
        u: 'j_idt104',
      });
    });
    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) {
    console.log(`Fetching data for ${plate}`);
    await this.launchPage();
    await this.submitForm(plate);
    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;
  }
}

export default CookieMonster;
