import Vorpal from "vorpal";
import { chromium } from "playwright";
import os from "os";
import fs from "fs";
import path from "path";

const __dirname = new URL(".", import.meta.url).pathname.replace(/^\//,'');
console.log(__dirname)
const vorpal = new Vorpal();

const contexts = {};

vorpal
    .command("new <name>")
    .alias("n")
    .action(async function (args, cb) {
        if (contexts[args.name]) {
            this.log("Context already exists");
            return cb();
        }

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

        // 启动浏览器
        const context = await chromium.launchPersistentContext(userDataDir, {
            headless: false,
            // proxy: {
            //     server: "199.188.92.93:8000",
            //     username: "proxy",
            //     password: "rPZHv9U",
            // },
            args: [
                "--window-position=0,0",
            ],
            userAgent:
                "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3105.3 Safari/537.36",
        });

        let accountInfo;
        try {
            accountInfo = JSON.parse(
                fs
                    .readFileSync(
                        path.join(
                            __dirname,
                            "validAccounts",
                            `${args.name}.json`
                        )
                    )
                    .toString()
            );
            context.addCookies(accountInfo.cookies);
        } catch (error) {
            this.log("accountInfo not found");
            return;
        }

        contexts[args.name] = context;

        context.on("page", (page) => {
            vorpal.log("New page created");

            page.on("close", async () => {
                vorpal.log("Page closed");
                accountInfo.cookies = await page.context().cookies();
                fs.writeFileSync(
                    path.join(__dirname, "validAccounts", `${args.name}.json`),
                    JSON.stringify(accountInfo, null, 4)
                );
            });
        });

        context.on("close", () => {
            vorpal.log("Context closed");
            delete contexts[args.name];
        });
        // 创建一个新的浏览器页面
        const page = await context.newPage();
        page.goto("https://www.paypal.com/myaccount/summary");

        cb();
    });

vorpal
    .command("close [name]")
    .alias("c")
    .option("-a, --all", "Close all contexts")
    .validate(function (args) {
        if (Object.keys(contexts).length === 0) {
            return "No context to close";
        }
        if (args.options.all && args.name) {
            return "Cannot use --all and a context name at the same time";
        }
        if (
            !args.options.all &&
            !args.name &&
            !Object.keys(contexts).length === 1
        ) {
            return "You must specify a context name or use --all";
        }
        return true;
    })
    .action(async function (args, cb) {
        this.log(args);
        if (args.options.all) {
            for (const name of Object.keys(contexts)) {
                await contexts[name].close();
                delete contexts[name];
            }
        } else if (args.name) {
            if (!contexts[args.name]) {
                this.log.error("Context not found");
                return cb();
            }
            await contexts[args.name].close();
            delete contexts[args.name];
        } else if (Object.keys(contexts).length === 1) {
            const name = Object.keys(contexts)[0];
            await contexts[name].close();
            delete contexts[name];
        }
    });

vorpal.delimiter("myapp$").show();
