const { By, until, Builder } = require("selenium-webdriver");
require("chromedriver");

(async function auto_test() {
  let driver = await new Builder().forBrowser("chrome").build();
  module.exports.driver = driver;

  try {
    // Link Mini-game
    await driver.get("https://app.adman.vn/api/preview/minigame.php?id=O4z25JLzP9");
    await driver.manage().window().maximize();
    await driver.manage().getTimeouts({ implicit: 3000, pageLoad: 3000, script: 3000 })

    // Load jQuery 2.2.4
    driver.executeScript(`
      var jquery_script = document.createElement('script');
      jquery_script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js';
      document.getElementsByTagName('head')[0].appendChild(jquery_script);
    `)
    driver.sleep(3000);
    await driver.executeScript('$ = window.jQuery;');

    // Tạo bảng kiểm tra lỗi
    const { checkList, checkListForm } = require("./check_work");
    const { renderTableCheck, createCheckList } = require("./table");
    const checkListHtml = driver.executeScript(createCheckList, checkList)
    await driver.executeScript(renderTableCheck, checkListHtml);

    // Xử lý bảng kiểm tra lỗi
    for (let item of checkList) {
      if (item.func) {
        await driver.executeScript(item.func).then((data) => {
          driver.executeScript(checkListForm, item.id, data);
        })
      }
    }

    // Xử lý Automation
    const { checkAuto } = require("./automation");

    for (let item of checkAuto) {
      if (item.action === 'click') {
        driver.wait(until.elementLocated(By.id(item.id)), 10000).click();
      } else if (item.action === 'sendKeys') {
        driver.wait(until.elementLocated(By.id(item.id)), 10000).sendKeys(item.value);
      } else if (item.action === 'function') {
        const newFunc = item.value
        newFunc();
      }
    }
  }

  catch (error) {
    console.log('error', error);

  } finally {
    // setTimeout(() => driver.quit(), 50000);

  }
})();