const { By, until } = require("selenium-webdriver");
let { driver } = require("./app");
const { checkListForm } = require("./check_work");

const checkAuto = [
  {
    name: 'buttonStartPopup',
    id: 'js-play-btn-popup',
    action: 'click',
  },
  {
    name: 'inputFormEmail',
    id: 'js-user-email',
    action: 'sendKeys',
    value: 'webdriver@gmail.com',
    key: 'email',
  },
  {
    name: 'inputFormName',
    id: 'js-user-name',
    action: 'sendKeys',
    value: 'webdrive',
    key: 'name',
  },
  {
    name: 'inputFormMobile',
    id: 'js-user-mobile',
    action: 'sendKeys',
    value: '0832256935',
    key: 'tel',
  },
  {
    name: 'spinBtn',
    id: 'js-spin-btn',
    action: 'click',
  },
  {
    name: 'playAgainAndChoseReward',
    action: 'function',
    value: playAgainAndChoseReward,
  },
]

// Kiểm tra element có tồn tại không
async function checkEleExitedByID(id) {
  try {
  }
  finally {
    return Object.keys(await driver.findElements(By.id(id))).length
  }
}

// Kiểm tra chọn giải thưởng
async function checkChoseReward() {
  try {
  }
  finally {
    const choseRewards = await driver.findElements(By.className("js-chose-reward-btn"));
    for (let item of choseRewards) {
      switch (Object.keys(await item.getText()).length > 0) {
        case true:
          await item.click();
          await driver.switchTo().alert().accept();
          await driver.executeScript(checkListForm, 'form-chon-giai-thuong', true)
          break;
        default:
          break;
      }
    }
  }
}

// Kiểm tra chơi lại, lượt chơi tối đa và chọn giải thưởng
async function playAgainAndChoseReward() {
  let playerTurns = 1;
  const repeatResetBtn = setInterval(async () => {
    if (await checkEleExitedByID('js-reset-btn') > 0) {
      let resetBtn = driver.wait(until.elementLocated(By.id("js-reset-btn")), 10000);
      resetBtn.click();
      playerTurns = playerTurns + 1;
    } else {
      clearInterval(repeatResetBtn);
      await driver.executeScript(checkListForm, 'form-luot-choi-toi-da', playerTurns)
      await checkChoseReward();
    }
  }, 15000)
}

const automation = {
  checkAuto
}
module.exports = automation;