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 accounts = fs
    .readFileSync("accounts.txt")
    .toString()
    .split("\n")
    .filter((i) => i.trim())
    .map((i) =>
        i
            .split("\t")
            .map((i) => i.trim())
            .filter((i) => i)
    )
    .map((i) => {
        const res = {};
        const m =
            /^(?<email>[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}):(?<pwd>.*)$/.exec(
                i[0]
            );
        if (i[18]) {
            res.cookies = JSON.parse(i[18].replace(/^Cookie[:：]/, ""));
            console.log(res.cookies);
        }
        if (m) {
            res.email = m.groups.email;
            res.pwd = m.groups.pwd;
        }

        return res;
    });

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

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;
    });
}

let context = null;
let i = 11;
vorpal.command("y").action(async function (args, cb) {
    fs.writeFileSync(
        path.join(__dirname, "validAccounts", `${accounts[i].email}.json`),
        JSON.stringify(
            {
                email: accounts[i].email,
                pwd: accounts[i].pwd,
                cookies: accounts[i].cookies,
            },
            null,
            4
        )
    );
    await context.close();
    cb();
});
vorpal.command("n").action(async function (args, cb) {
    await context.close();
    cb();
});

async function start() {
    for (; i < accounts.length; i++) {
        const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "myapp"));
        const pathToExtension = path.join(
            __dirname,
            "fngmhnnpilhplaeedifhccceomclgfbg"
        );

        // 启动浏览器
        context = await chromium.launchPersistentContext(userDataDir, {
            headless: false,
            // proxy: {
            //     server: "199.188.92.93:8000",
            //     username: "proxy",
            //     password: "rPZHv9U",
            // },
            args: [
                `--disable-extensions-except=${pathToExtension}`,
                `--load-extension=${pathToExtension}`,
            ],
            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(accounts[i].cookies));
        const page = await context.newPage();
        await page.goto("https://paypal.com/myaccount/summary");

        await new Promise((resolve) => {
            context.on("close", resolve);
        });
    }
}

vorpal.command("start").action(async function (args, cb) {
    start();
    cb();
});

vorpal.delimiter(">").show();
