import { rand } from "@c3/utils";
import _ from "lodash";
import { test } from "@playwright/test";
import path from "node:path";
import { chromium } from "playwright";
class Animal {
  constructor(name) {
    this.name = name;
  }
}
class Mammal extends Animal {
  say() {
    console.log("say");
  }
}
class Cat extends Mammal {
  say() {
    console.log("meow");
  }
}
const gtext = `This handy tool helps you create dummy text for all your layout needs.We are gradually adding new functionality and we welcome your suggestions and feedback.Please feel free to send us any additional dummy texts.
`;
const gtextArray = gtext.split(" ");
const getRandomText = () => _.shuffle(gtextArray).join(" ");
const getRandomWord = () => _.sample(gtextArray) || "hello-world";
const randUserApi = "https://jsonplaceholder.typicode.com/users";
const getRandomUser = async () => {
  const data = await fetch(randUserApi);
  return data.json();
};
let gid = 0;
const mock = {
  getRandomPic: (width = 160 * 6, height = 90 * 6) => {
    return `https://picsum.photos/id/${rand(10, 100)}/${width}/${height}.jpg`;
  },
  getRandomText,
  getRandomWord,
  getId: () => `uniq-id-${gid++}`,
  getRandomUser,
  getRandomColor: () => {
    return `#${Math.floor(Math.random() * 16777215).toString(16)}`;
  }
};
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 metamask = {
  approve() {
    console.log();
  },
  reject() {
    console.log("x");
  }
};
const waitForMetaMask = async (metamaskPage, selctor, option) => {
  let isVisible = false;
  while (!isVisible) {
    await metamaskPage.waitForTimeout(1e3);
    await metamaskPage.reload();
    isVisible = await metamaskPage.locator(selctor, option).isVisible();
  }
  return metamaskPage.locator(selctor, option);
};
const SELECTORS = {
  confirmBtn: ["button", { hasText: "Confirm" }],
  approveBtn: ["button", { hasText: "Approve" }],
  switchNetworkBtn: ["button", { hasText: "Switch network" }],
  rejectBtn: ["button", { hasText: "Reject" }],
  nextBtn: ["button", { hasText: "Next" }],
  connectBtn: ["button", { hasText: "Connect" }]
};
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 { Animal, Cat, Mammal, SELECTORS, metamask, mock, printPageUrls, signinWallet, testWithMetaMask, waitForMetaMask };
