import Vorpal from "vorpal";
import { chromium } from "playwright";
import os from "os";
import fs from "fs";
import path from "path";
import rawCookies from "./cookies.js";
import { setTimeout } from "timers/promises";

const __dirname = new URL(".", import.meta.url).pathname;

function formatCookies(cookies) {
    return cookies.map((i) => {
        switch (i.sameSite) {
            case "no_restriction":
            case "None":
                i.sameSite = "None";
                break;
            case "lax":
            case "Lax":
                i.sameSite = "Lax";
                break;
            case "strict":
            case "Strict":
                i.sameSite = "Strict";
                break;
            default:
                i.sameSite = undefined;
                break;
        }
        return i;
    });
}

const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "myapp"));
const pathToExtension = path.join(
    __dirname,
    "fngmhnnpilhplaeedifhccceomclgfbg"
);

// 启动浏览器
let context = await chromium.launchPersistentContext(userDataDir, {
    headless: false,
    locale: "en-US",
    timezoneId: "America/New_York",
    // proxy: {
    //     server: "199.188.92.93:8000",
    //     username: "proxy",
    //     password: "rPZHv9U",
    // },
    args: [
        `--disable-extensions-except=${pathToExtension}`,
        `--load-extension=${pathToExtension}`,
        "--window-position=-1280,0",
    ],
    userAgent:
        "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3105.3 Safari/537.36",
});
context.addCookies(
    formatCookies([
        {
            id: 0,
            name: "enforce_policy",
            value: "ccpa",
            path: "/",
            hostOnly: false,
            httpOnly: false,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
        {
            id: 1,
            name: "id_token",
            value: "idtokencbd59a20f80342fa884a1c954aba0e9c",
            path: "/",
            hostOnly: false,
            httpOnly: true,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
        {
            id: 2,
            name: "AV894Kt2TSumQQrJwe-8mzmyREO",
            value: "S23AAPsIRj_t4bk_JoxBuz7gZvDEi4soSgRMB5ILiBwoPDcUvfZTPO8jPdUkwU-Rpbp6DwrOQ0f-TiOavMID82avmOzxa0iLw",
            path: "/",
            hostOnly: false,
            httpOnly: true,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
        {
            id: 3,
            name: "LANG",
            value: "en_US%253BUS",
            path: "/",
            hostOnly: false,
            httpOnly: true,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
        {
            id: 4,
            name: "tsrce",
            value: "unifiedloginnodeweb",
            path: "/",
            hostOnly: false,
            httpOnly: true,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
        {
            id: 5,
            name: "HaC80bwXscjqZ7KM6VOxULOB534",
            value: "iFfqWZ5pGNHC4gNXjYOPGiwzofBTyMHvUf7y5WJn8xxj4YlkiHnRclEj2MnvF1wtxWLKaHFH3pw3a0mT0ayZOtfNRzqEYZvt2ICIIrbtBxDkFR3XrbQHb0KCXZ0ejAOdKx0r1G",
            path: "/",
            hostOnly: false,
            httpOnly: true,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
        {
            id: 6,
            name: "DPz73K5mY4nlBaZpzRkjI3ZzAY3QMmrP",
            value: "S23AAPsIRj_t4bk_JoxBuz7gZvDEi4soSgRMB5ILiBwoPDcUvfZTPO8jPdUkwU-Rpbp6DwrOQ0f-TiOavMID82avmOzxa0iLw",
            path: "/",
            hostOnly: false,
            httpOnly: true,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
        {
            id: 7,
            name: "x-pp-s",
            value: "eyJ0IjoiMTcwOTA1MjU4NDc2NSIsImwiOiIwIiwibSI6IjAifQ",
            path: "/",
            hostOnly: false,
            httpOnly: true,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
        {
            id: 8,
            name: "login_email",
            value: "shannonlilmomma%40aol.com",
            path: "/",
            hostOnly: false,
            httpOnly: true,
            domain: ".paypal.com",
            expirationDate: 1711644583,
            storeId: "0",
            sameSite: "no_restriction",
            secure: true,
        },
    ])
);
const page = await context.newPage();
await page.goto("https://paypal.com/myaccount/summary");
await page.waitForLoadState("networkidle");

const url = await page.url();
console.log(url);

if ((await page.locator('//*[text()="Security Challenge"]').count()) > 0) {
    await page.waitForURL("*");
}

if (/signin/.test(url)) {
    if ((await page.locator('//button[text()="Get a Code"]').count()) > 0) {
        // await page.locator('//*[@id="loginWithPassword" and not(@hidden)]').click();
        await page.locator('//*[text()="Try another way"]').first().click();
        await page.locator('//*[@id="loginWithPassword"]').first().click();
    }
}

if(await page.locator('#password').count() > 0) {
    await page.fill('#password', 'password');
    await page.locator('#btnLogin').first().click();
}