import { test } from "@playwright/test";
import path from "node:path";
import { chromium } from "playwright";
const signinWallet = async (page) => {
  await page.goto(
    "chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html#initialize/welcome"
  );
  await page.locator("text=Get Started").click();
  await page.waitForURL(
    "chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html#initialize/select-action"
  );
  await page.locator("text=Import wallet").click();
  await page.waitForURL(
    "chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html#initialize/metametrics-opt-in"
  );
  await page.locator('[data-testid="page-container-footer-next"]').click();
  await page.waitForURL(
    "chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html#initialize/create-password/import-with-seed-phrase"
  );
  await page.locator("select").selectOption("24");
  const pwdstring = "hockey   dilemma   magic   rigid   blade   crawl   soldier   screen   mind   siege   disorder   hint   ramp   solid   flat   caution   swamp   anger   attend   trim   tell   obscure   rice   math";
  const pwds = pwdstring.split(/\s+/);
  for (const [idx, pwd] of Object.entries(pwds)) {
    const ele = page.locator(`[data-testid="import-srp__srp-word-${idx}"]`);
    await ele.click();
    await ele.fill(pwd);
  }
  await page.locator("text=I have read and agree to the Terms of Use").click();
  await page.locator("#password").click();
  await page.locator("#password").fill("Over123456");
  await page.locator("#confirm-password").click();
  await page.locator("#confirm-password").fill("Over123456");
  await page.locator('button:has-text("Import")').click();
  await page.waitForURL(
    "chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html#initialize/end-of-flow"
  );
  await page.locator("text=All Done").click();
  await page.locator(".popover-header__title button").click();
};
const testWithMetaMask = test.extend({
  context: async ({}, use) => {
    const pathToExtension = path.join(__dirname, "./extension");
    const context = await chromium.launchPersistentContext("", {
      devtools: false,
      headless: false,
      timeout: 0,
      args: [
        `--disable-extensions-except=${pathToExtension}`,
        `--load-extension=${pathToExtension}`
      ]
    });
    await use(context);
    await context.close();
  },
  metaMaskPage: async ({ context, extensionId }, use) => {
    const extensionURL = `chrome-extension://${extensionId}/popup.html`;
    const pages = context.pages();
    const page = pages.length > 0 ? pages[0] : await context.newPage();
    await signinWallet(page);
    await page.goto(extensionURL);
    for (const p of context.pages()) {
      if (p.url().includes("home.html#initialize/welcome")) {
        await p.close();
      }
    }
    await use(page);
  },
  extensionId: async ({ context }, use) => {
    let [background] = context.backgroundPages();
    if (!background) {
      background = await context.waitForEvent("backgroundpage");
    }
    const extensionId = background.url().split("/")[2];
    await use(extensionId);
  }
});
const SELECTORS = {
  confirmFeeEtcBtn: ["button", { hasText: "Confirm" }],
  approveAddNetworkBtn: ["button", { hasText: "Approve" }],
  switchNetworkBtn: ["button", { hasText: "Switch network" }],
  rejectBtn: ["button", { hasText: "Reject" }],
  nextBtn: ["button", { hasText: "Next" }],
  connectBtn: ["button", { hasText: "Connect" }]
};
const waitForMetaMask = async (metamaskPage, selector, option) => {
  let isVisible = false;
  while (!isVisible) {
    await metamaskPage.reload({ waitUntil: "load" });
    await metamaskPage.waitForTimeout(1500);
    isVisible = await metamaskPage.locator(selector, option).isVisible();
  }
  return metamaskPage.locator(selector, option);
};
class Metamask {
  constructor(metaMaskPage) {
    this.metaMaskPage = metaMaskPage;
  }
  async connect2Wallet() {
    await waitForMetaMask(this.metaMaskPage, ...SELECTORS.nextBtn);
    await this.metaMaskPage.locator(...SELECTORS.nextBtn).click();
    await this.metaMaskPage.locator(...SELECTORS.connectBtn).click();
  }
  async addAndSwitchNetwork() {
    await waitForMetaMask(this.metaMaskPage, ...SELECTORS.approveAddNetworkBtn);
    await this.metaMaskPage.locator(...SELECTORS.approveAddNetworkBtn).click();
    await this.metaMaskPage.locator(...SELECTORS.switchNetworkBtn).click();
  }
  async confirmTx() {
    await waitForMetaMask(this.metaMaskPage, ...SELECTORS.confirmFeeEtcBtn);
    await this.metaMaskPage.locator(...SELECTORS.confirmFeeEtcBtn).click();
  }
}
const printPageUrls = (ctx) => {
  console.log("\n---pages begin----");
  ctx.pages().forEach((e) => console.log("pageurl", e.url()));
  ctx.backgroundPages().forEach((e) => console.log("background page url", e.url()));
  console.log("---pages end----\n");
};
export { Metamask, SELECTORS, printPageUrls, signinWallet, testWithMetaMask, waitForMetaMask };
