// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.

import { Page } from "playwright";
import { SmokeTestLogger } from "./helper/smokeTestLogger";
import { app, screenshots } from "./main";
import * as assert from "assert";

export function startCommandPaletteTests(): void {
    describe("CommandPaletteTest", () => {
        async function initApp(): Promise<Page> {
            await app.launch();
            return app.getMainPage();
        }

        async function dispose() {
            try {
                if (this.currentTest?.state === "failed") {
                    SmokeTestLogger.info("Test failed, taking screenshot ...");
                    await screenshots.takeScreenshots(
                        this.currentTest.parent?.title || "Others",
                        this.currentTest.title.replace(/\s+/g, "_"),
                    );
                }
            } catch (error) {
                // Log error when screenshot get error, but not throw exception
                SmokeTestLogger.log(`Error with taking screenshot: ${error}`);
            }

            try {
                SmokeTestLogger.info(`Dispose test: "${this.currentTest.title}" ...`);
                if (app) {
                    await app.close();
                }
            } catch (error) {
                SmokeTestLogger.error(`Error while dispose: ${error}`);
            }
        }

        afterEach(dispose);

        it("Verify react native command is visible in command palette", async () => {
            const page = await initApp();

            const cmdKey = process.platform === "darwin" ? "Meta" : "Control";
            await page.keyboard.press(`${cmdKey}+Shift+P`);
            await page.waitForSelector(".quick-input-widget", { timeout: 10000 });

            await page.keyboard.type("React Native: Start Packager");
            const option = await page.waitForSelector("#quickInput_list .monaco-list-row.focused", {
                timeout: 30000,
            });

            const value = await option.getAttribute("aria-label");
            assert.ok(value?.includes("React Native: Start Packager"));
        });
    });
}
