/*
This file is part of the Notesnook project (https://notesnook.com/)

Copyright (C) 2023 Streetwriters (Private) Limited

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import type { Page } from "@playwright/test";
import {
  downloadAndReadFile,
  getTestId,
  IS_DESKTOP_TESTS,
  uploadFile
} from "../utils";
import {
  confirmDialog,
  fillConfirmPasswordDialog,
  fillPasswordDialog,
  waitForDialog,
  waitToHaveText
} from "./utils";
import { NavigationMenuModel } from "./navigation-menu.model";
import { AppModel } from "./app.model";
import { getAppFromPage } from "../../../desktop/__tests__/electron-test/utils";
import { readFile } from "node:fs/promises";

export class SettingsViewModel {
  private readonly page: Page;
  private readonly navigation: NavigationMenuModel;

  constructor(page: Page) {
    this.page = page;
    this.navigation = new NavigationMenuModel(page, "settings-navigation-menu");
  }

  async close() {
    await this.page.locator(getTestId("settings-search")).focus();
    await this.page.waitForTimeout(100);
    await this.page.keyboard.press("Escape");
    await this.page.waitForTimeout(1000);
  }

  async logout() {
    const item = await this.navigation.findItem("Profile");
    await item?.click();

    const logoutButton = this.page
      .locator(getTestId("setting-logout"))
      .locator("button");

    await logoutButton.click();
    await confirmDialog(this.page.locator(getTestId("confirm-dialog")));

    await this.page
      .locator(getTestId("progress-dialog"))
      .waitFor({ state: "hidden" });

    await this.page
      .locator(getTestId("logged-in"))
      .waitFor({ state: "hidden" });
  }

  async getRecoveryKey(password: string) {
    const item = await this.navigation.findItem("Profile");
    await item?.click();

    const backupRecoveryKeyButton = this.page
      .locator(getTestId("setting-recovery-key"))
      .locator("button");

    await backupRecoveryKeyButton.click();
    await fillPasswordDialog(this.page, password);

    await waitToHaveText(this.page, "recovery-key");

    const key = await this.page
      .locator(getTestId("recovery-key"))
      .textContent();

    const dialog = this.page.locator(getTestId("recovery-key-dialog"));
    await confirmDialog(dialog);
    return key;
  }

  async isLoggedIn() {
    const loggedInButton = this.page.locator(getTestId("logged-in"));
    return await loggedInButton.isVisible();
  }

  async isBackupEncryptionEnabled(state: boolean) {
    const encyptBackups = this.page
      .locator(getTestId("setting-encrypt-backups"))
      .locator(
        state ? `input[data-checked="true"]` : `input[data-checked="false"]`
      );
    await encyptBackups.waitFor({ state: "visible" });
    return (await encyptBackups.getAttribute("data-checked")) === "true";
  }

  async toggleBackupEncryption(password?: string) {
    const item = await this.navigation.findItem("Backup & export");
    await item?.click();

    const encyptBackups = this.page
      .locator(getTestId("setting-encrypt-backups"))
      .locator("label");

    await encyptBackups.click();

    if (password) await fillPasswordDialog(this.page, password);
  }

  async createBackup(password?: string) {
    const item = await this.navigation.findItem("Backup & export");
    await item?.click();

    const saveBackup = async () => {
      const backupData = this.page
        .locator(getTestId("setting-create-backup"))
        .locator("select");
      await backupData.selectOption({ value: "partial", label: "Backup" });
      if (password) await fillPasswordDialog(this.page, password);
    };

    if (IS_DESKTOP_TESTS) {
      await saveBackup();
      const toast = new AppModel(this.page).toasts.toasts.locator(
        getTestId("toast-message")
      );
      await toast.waitFor();
      const backupPath = (await toast.textContent())
        ?.replace("Backup saved at", "")
        .trim();
      if (!backupPath)
        throw new Error("Backup path not found in toast message");
      const app = getAppFromPage(this.page);
      const resolvedDocumentPath = await app.evaluate(({ app }) =>
        app.getPath("documents")
      );
      const resolvedBackupPath = backupPath.startsWith("documents")
        ? backupPath.replace("documents", resolvedDocumentPath)
        : backupPath;
      return await readFile(resolvedBackupPath, "utf-8");
    } else return await downloadAndReadFile(this.page, saveBackup, "utf-8");
  }

  async restoreData(filename: string, password?: string) {
    const item = await this.navigation.findItem("Backup & export");
    await item?.click();

    const restoreBackup = this.page
      .locator(getTestId("setting-restore-backup"))
      .locator("button");

    await uploadFile(this.page, restoreBackup, filename);
    if (password) await fillPasswordDialog(this.page, password);
  }

  async selectImageCompression(option: { value: string; label: string }) {
    const item = await this.navigation.findItem("Behaviour");
    await item?.click();

    const imageCompressionDropdown = this.page
      .locator(getTestId("setting-image-compression"))
      .locator("select");

    await imageCompressionDropdown.selectOption(option);
  }

  async enableAppLock(userPassword: string, appLockPassword: string) {
    const item = await this.navigation.findItem("App lock");
    await item?.click();

    const appLockSwitch = this.page
      .locator(getTestId("setting-enable-app-lock"))
      .locator("label");

    await appLockSwitch.click();
    await fillPasswordDialog(this.page, userPassword);
    await this.page.waitForTimeout(500);
    await fillConfirmPasswordDialog(this.page, appLockPassword);
    await this.page.waitForTimeout(500);
  }

  async disableAppLock(appLockPassword: string) {
    const item = await this.navigation.findItem("App lock");
    await item?.click();

    const appLockSwitch = this.page
      .locator(getTestId("setting-enable-app-lock"))
      .locator("label");

    await appLockSwitch.click();
    await fillPasswordDialog(this.page, appLockPassword);
    await this.page.waitForTimeout(100);
  }

  async setTitleFormat(format: string) {
    const item = await this.navigation.findItem("Editor");
    await item?.click();

    const titleFormatInput = this.page
      .locator(getTestId("setting-default-title"))
      .locator("input");
    await titleFormatInput.fill(format);
  }

  async checkForUpdates() {
    await this.navigation.waitFor();

    const item = await this.navigation.findItem("About");
    await item?.click();

    const button = this.page
      .locator(getTestId("setting-version"))
      .locator("button", { hasText: "Check for updates" });
    await button.click();
  }
}
