import { LisioBooleanParameterNames, LisioNumericParameterNames, LisioParameter, LisioParameterFactory, LisioParameterNames, LisioProfileFactory, LisioProfileNames, LisioStringParameterNames, LisioUser, LisioUserParsed, StorageController } from "@lisio/lisio-profils";
import { CompressorController } from "../compressor-controller";
import ExtensionPolyfill from "../../../extension-polyfill";

const isFirefoxOrSafari =
  /safari|firefox/.test(navigator.userAgent.toLowerCase()) &&
  !navigator.userAgent.toLowerCase().includes("chrome");

/**
 * Checks whether the extension flagged the reading-mode side panel as closed ("close-reading-mode").
 * Outside the extension, or when the extension storage can't be read, there is no flag.
 * @returns Returns a promise containing whether reading-mode profiles have to be dropped
 */
async function hasPendingCloseReadingMode(): Promise<boolean> {
  if (__BUILD_TARGET__ !== "extension") {
    return false;
  }
  try {
    const closeReadingMode = await ExtensionPolyfill.current.storage.local.get("close-reading-mode");
    return closeReadingMode["close-reading-mode"] === "true";
  } catch {
    return false;
  }
}


abstract class UserControllerStorage{

  /**
   * protected attribute to store next user number
   * @source
   */
  protected _nextUserNumber: number = 1;

  /**
   * protected attribute to store current user selected from storage
   * @source
   */
  protected _currentUser?: LisioUser;

  /**
   * protected attribute to store all usernames from storage
   * @source
   */
  protected _usernames: string[] = [];

  /**
   * protected attribute to store all users from storage
   * @source
   */
  protected _users: Map<string, LisioUser> = new Map<string, LisioUser>();

    /**
   * protected attribute to store all storage controller
   * @source
   */
  protected _storageControllers: StorageController[] = [];

  /**
   * Getter for attribute {@link _currentUser | _currentUser}
   * @returns Returns _currentUser attribute
   * @source
   */
  public get currentUser(): LisioUser | undefined {
    return this._currentUser;
  }

  /**
   * Getter for attribute {@link _users | _users}
   * @returns Returns _users attribute
   * @source
   */
  public get users(): Map<string, LisioUser> {
    return this._users;
  }

  /**
   * Getter for attribute {@link _usernames | _usernames}
   * @returns Returns _usernames attribute
   * @source
   */
  public get usernames(): string[] {
    return this._usernames;
  }

  /**
   * Getter for attribute {@link _storageControllers | _storageControllers}
   * @returns Returns _storageControllers attribute
   * @source
   */
  public get storageControllers(): StorageController[] {
    return this._storageControllers;
  }

  public get nextUserNumber(){
    return this._nextUserNumber;
  }

  public async deleteUser(username: string): Promise<void> {
    if (this._users.size > 1) {
      for (const storageController of this._storageControllers) {
        await storageController.deleteUser(username);
      }
      this._usernames.splice(this._usernames.indexOf(username), 1);
      this._users.delete(username);
    }
  }

  public async renameUser(newUsername: string): Promise<string> {
    if (this._users.get(newUsername) == undefined) {
      const currentUsername = this.currentUser!.name;
      this._currentUser!.name = newUsername;
      this._users.delete(currentUsername);
      this._usernames[this._usernames.indexOf(currentUsername)] = newUsername;
      for (const storageController of this._storageControllers) {
        await storageController.renameUser(currentUsername, newUsername);
      }
      this._users.set(newUsername, this._currentUser!);
      return currentUsername;
    }else{
      return "";
    }
  }

  public async deleteAllUsers(): Promise<void> {
    for (const storageController of this._storageControllers) {
      await storageController.deleteAllUsers();
    }
    this.setCurrentUser(undefined);
    this._usernames = [];
    this._users.clear();
    this._nextUserNumber = 1;
  }

  public async createNewUser(): Promise<{
    username: string;
    isActiveParameter: LisioParameter;
    alreadyHasUser: boolean;
  }> {
    const isActiveParameter: LisioParameter =
      LisioParameterFactory.current.buildLisioParameter(
        LisioBooleanParameterNames.IS_ACTIVE,
        true,
      );
    this._nextUserNumber = this.getNewUserNumber();
    const newUser: LisioUser = new LisioUser(
      `Utilisateur-${this._nextUserNumber}`,
      true,
      new Map<LisioParameterNames, LisioParameter>(
        this._currentUser == undefined
          ? [[LisioBooleanParameterNames.IS_ACTIVE, isActiveParameter]]
          : new Map(this._currentUser.customParameters),
      ),
      this._currentUser == undefined ? [] : [...this._currentUser.profiles],
    );
    const alreadyHasUser = this._currentUser != undefined;
    for (const storageController of this._storageControllers) {
      await storageController.setUser(newUser);
    }
    if (this._currentUser != undefined) {
      for (const storageController of this._storageControllers) {
        await storageController.switchSelectedUser(newUser.name);
      }
      const user = this._users.get(this._currentUser.name);
      if (user != undefined) {
        user.isSelected = false;
      }
    }
    this._usernames.push(newUser.name);
    this.setCurrentUser(newUser);
    this._users.set(newUser.name, newUser);
    this._nextUserNumber++;
    return {username: newUser.name, isActiveParameter, alreadyHasUser};
  }

  public async updateUserBoolean(
    name: LisioBooleanParameterNames | LisioProfileNames,
    value: boolean,
  ): Promise<void> {
    if (name.toUpperCase() in LisioBooleanParameterNames) {
      if (this._currentUser == undefined) {
        await this.createNewUser();
      }
      if (value) {
        this._currentUser?.customParameters.set(
          name as LisioBooleanParameterNames,
          LisioParameterFactory.current.buildLisioParameter(
            name as LisioBooleanParameterNames,
            value,
          ),
        );
      } else {
        this._currentUser?.customParameters.delete(
          name as LisioBooleanParameterNames,
        );
      }
      for (const storageController of this._storageControllers) {
        await storageController.updateUser(
          this._currentUser?.formatForSaving()!,
          value
            ? {
                add: {
                  parameters: [
                    { name: name as LisioBooleanParameterNames, value },
                  ],
                },
              }
            : {
                remove: {
                  parameters: [name as LisioBooleanParameterNames],
                },
              },
        );
      }
    } else {
      if (this._currentUser == undefined) {
        await this.createNewUser();
      }
      if (value) {
        this._currentUser?.profiles.push(name as LisioProfileNames);
      } else {
        // indexOf -1 would make splice drop the last profile instead.
        const profileIndex = this._currentUser?.profiles.indexOf(name as LisioProfileNames) ?? -1;
        if (profileIndex !== -1) {
          this._currentUser?.profiles.splice(profileIndex, 1);
        }
      }
      for (const storageController of this._storageControllers) {
        await storageController.updateUser(
          this._currentUser?.formatForSaving()!,
          value
            ? { add: { profiles: [{ name: name as LisioProfileNames }] } }
            : {
                remove: { profiles: [name as LisioProfileNames] },
              },
        );
      }
    }
    // No deletion check here: the caller runs it once the update is done (see UserController),
    // a concurrent second check would put the deleted user back into _users.
  }

  public async updateUserString(
    name: LisioStringParameterNames,
    value: string,
    isDefault: boolean,
  ): Promise<void> {
    if (this._currentUser == undefined) {
      await this.createNewUser();
    }
    if (isDefault) {
      this._currentUser?.customParameters.delete(name);
    } else {
      this._currentUser?.customParameters.set(
        name,
        LisioParameterFactory.current.buildLisioParameter(name, value),
      );
    }
    for (const storageController of this._storageControllers) {
      await storageController.updateUser(
        this._currentUser?.formatForSaving()!,
        isDefault
          ? {
              remove: { parameters: [name] },
            }
          : {
              update: [
                {
                  name,
                  value,
                },
              ],
            },
      );
    }
    // No deletion check here: the caller runs it once the update is done (see UserController),
    // a concurrent second check would put the deleted user back into _users.
  }

  public async updateUserNumber(
    name: LisioNumericParameterNames,
    value: number,
    isDefault: boolean,
  ): Promise<void> {
    if (this._currentUser == undefined) {
      await this.createNewUser();
    }
    if (isDefault) {
      this._currentUser?.customParameters.delete(name);
    } else {
      this._currentUser?.customParameters.set(
        name,
        LisioParameterFactory.current.buildLisioParameter(name, value),
      );
    }
    for (const storageController of this._storageControllers) {
      await storageController.updateUser(
        this._currentUser?.formatForSaving()!,
        isDefault
          ? {
              remove: { parameters: [name] },
            }
          : {
              update: [
                {
                  name,
                  value,
                },
              ],
            },
      );
    }
    // No deletion check here: the caller runs it once the update is done (see UserController),
    // a concurrent second check would put the deleted user back into _users.
  }

  public async checkIfUserNeedToBeDeleted(): Promise<boolean> {
    if (this._currentUser != undefined) {
      if (
        ((this._currentUser.customParameters.size === 1 &&
          (this._currentUser.customParameters.has(
            LisioBooleanParameterNames.IS_ACTIVE,
          ) ||
            this._currentUser.customParameters.has(
              LisioBooleanParameterNames.BOOK_PAGE,
            ))) ||
          (this._currentUser.customParameters.size === 0 &&
            !this._currentUser.customParameters.has(
              LisioBooleanParameterNames.IS_ACTIVE,
            ))) &&
        this._currentUser.profiles.length === 0 &&
        // Count from _users (keyed by name, also behind get-users-size and the management button):
        // _usernames is an array that concurrent get-all-users/create-new-user calls can fill twice.
        this._users.size <= 1
      ) {
        // Captured before awaiting: concurrent checks (e.g. reset turning every
        // feature off at once) can clear _currentUser while this one awaits.
        const deletedName = this._currentUser.name;
        this._usernames = this._usernames.filter((name) => name !== deletedName);
        for (const storageController of this._storageControllers) {
          await storageController.deleteUser(deletedName);
        }
        this._users.delete(deletedName);
        // Forget the deleted user: a later check would put it back into _users,
        // and the next update has to create a fresh user.
        this.setCurrentUser(undefined);
        return true;
      } else {
        this._users.set(this._currentUser.name, this._currentUser);
        return false;
      }
    }else{
      return false;
    }
  }

  public async getSelectedUser(): Promise<void> {
    for (const storageController of this._storageControllers) {
      const savedUser = await storageController.getSelectedUser().catch(() => {
        if (!isFirefoxOrSafari) {
          storageController.deleteAllUsers();
        }
      });
      if (savedUser != undefined) {
        this.setCurrentUser(savedUser);
        // Reading-mode profiles are only dropped once the extension has flagged the reader as closed,
        // otherwise opening the popup would turn reading mode off and close the side panel.
        const hasToCloseReadingMode = await hasPendingCloseReadingMode();
        if(hasToCloseReadingMode && this._currentUser != undefined && this._currentUser.profiles.some((profile)=>LisioProfileFactory.current.buildLisioProfile(profile).parameters.has(LisioBooleanParameterNames.READING_MODE))){
          const profilesToRemove = savedUser.profiles.filter((profile)=>LisioProfileFactory.current.buildLisioProfile(profile).parameters.has(LisioBooleanParameterNames.READING_MODE))
          for(const profileToRemove of profilesToRemove){
            savedUser.profiles.splice(savedUser.profiles.indexOf(profileToRemove), 1);
            await this.updateUserBoolean(profileToRemove, false);
          }
          await this.checkIfUserNeedToBeDeleted();
          for (const user of this._users.values()) {
            storageController.setUser(user);
          }
        }
      }
    }
  }

  public async getNextUserNumber(): Promise<void> {
    this._nextUserNumber = this.getNewUserNumber();
  }

  /**
   * Returns the position the new user will have in the users list, so its name
   * matches its radio input. Skips numbers already taken by an existing user.
   */
  private getNewUserNumber(): number {
    let userNumber: number = this._users.size + 1;
    while (this._users.has(`Utilisateur-${userNumber}`)) {
      userNumber++;
    }
    return userNumber;
  }

  public async getAllUsers(): Promise<void> {
    let savedUsers: LisioUserParsed[] | undefined = undefined;
    for (const storageController of this._storageControllers) {
      if (savedUsers == undefined || savedUsers.length == 0) {
        savedUsers = await storageController.getAllUsers();
      }
    }
    if (savedUsers != undefined) {
      savedUsers.sort((a, b) => a.name.localeCompare(b.name));
      // Rebuild instead of appending: this runs on every get-all-users / get-usernames call,
      // and duplicates break the single-user check in checkIfUserNeedToBeDeleted.
      this._usernames = [];
      for (const savedUser of savedUsers) {
        this._usernames.push(savedUser.name);
        const parameterMap: Map<LisioParameterNames, LisioParameter> = new Map<
      LisioParameterNames,
      LisioParameter
    >(
        savedUser.customParameters.map((customParameter) => [
          customParameter.name,
          LisioParameterFactory.current.buildLisioParameter(
            customParameter.name,
            customParameter.value as string | number | boolean,
          ),
        ]),
      );
      this._users.set(savedUser.name, new LisioUser(
        savedUser.name,
        savedUser.isSelected,
        parameterMap,
        savedUser.profiles,
      ));
      }
    }
  }

  public async disableAllBookPageOrReading(): Promise<LisioProfileNames[]> {
    const bookPageReadingProfileName: LisioProfileNames[] = [];
    if (this._currentUser != undefined) {
      for (const profilName of [...this._currentUser.profiles]) {
        const profile =
          LisioProfileFactory.current.buildLisioProfile(profilName);
        if (
          profile.parameters.has(LisioBooleanParameterNames.BOOK_PAGE) ||
          profile.parameters.has(LisioBooleanParameterNames.READING_MODE)
        ) {
          await this.updateUserBoolean(profile.name, false);
          bookPageReadingProfileName.push(profilName);
        }
      }

      if (
        this._currentUser.customParameters.has(
          LisioStringParameterNames.UNDERLINE_RED,
        )
      ) {
        await this.updateUserString(
          LisioStringParameterNames.UNDERLINE_RED,
          "",
          true,
        );
      }
      if (
        this._currentUser.customParameters.has(
          LisioStringParameterNames.UNDERLINE_GREEN,
        )
      ) {
        await this.updateUserString(
          LisioStringParameterNames.UNDERLINE_GREEN,
          "",
          true,
        );
      }
      if (
        this._currentUser.customParameters.has(
          LisioStringParameterNames.UNDERLINE_BLUE,
        )
      ) {
        await this.updateUserString(
          LisioStringParameterNames.UNDERLINE_BLUE,
          "",
          true,
        );
      }
      if (
        this._currentUser.customParameters.has(
          LisioBooleanParameterNames.BOOK_PAGE,
        ) ||
        this._currentUser.customParameters.has(
          LisioBooleanParameterNames.READING_MODE,
        )
      ) {
        await this.updateUserBoolean(LisioBooleanParameterNames.BOOK_PAGE, false);
        await this.updateUserBoolean(LisioBooleanParameterNames.READING_MODE, false);
      }
    }
    return bookPageReadingProfileName;
  }

  public async switchSelectedUser(username: string): Promise<{profiles: LisioProfileNames[], parameters: LisioParameter[]}> {
    if (this._users.get(username) == undefined) {
      return {profiles: [], parameters: []};
    }
    if (
      this._currentUser != undefined &&
      this._users.has(this._currentUser.name)
    ) {
      this._users.get(this._currentUser.name)!.isSelected = false;
    }
    const isSameUsername = this._currentUser?.name == username;
    let lastUser: LisioUser | undefined = this._currentUser;
    for (const storageController of this._storageControllers) {
      if (this._currentUser == undefined || !isSameUsername) {
          lastUser = await storageController.switchSelectedUser(username);
      }
    }
    this.setCurrentUser(lastUser);
    if (this._currentUser == undefined) {
      return {profiles: [], parameters: []};
    }
    this._users.get(username)!.isSelected = true;
    this._currentUser.customParameters.set(
      LisioBooleanParameterNames.IS_ACTIVE,
      LisioParameterFactory.current.buildLisioParameter(
        LisioBooleanParameterNames.IS_ACTIVE,
        true,
      ),
    );
    return {profiles: this._currentUser.profiles || [], parameters: [...this._currentUser?.customParameters?.values()]}
  }

  protected setCurrentUser(value: LisioUser | undefined){
    this._currentUser = value;
  }

    public async synchronizeFromUrlQuery(urlQueries: string[]): Promise<boolean> {
    // Decode everything first: users already stored are only cleared once the
    // query is known to be valid, so a malformed query never wipes them
    let usernames: string[] = [];
    let parsedUsers: LisioUserParsed[] = [];
    try {
      for (const urlQuery of urlQueries) {
        const match = urlQuery.match(/(\w+)=(.+)/);
        if (match != null) {
          if (match[1] === "lisioUsernames") {
            usernames = JSON.parse(atob(match[2]));
          } else if (match[1] === "lisioUsers") {
            parsedUsers = CompressorController.current.decodeUsers(match[2]);
          }
        }
      }
    } catch (error) {
      console.error("Unable to decode users from url query, stored users are kept", error);
      return this._currentUser == undefined;
    }

    this.setCurrentUser(undefined);
    this._usernames = usernames;
    this._users.clear();
    for (const storageController of this._storageControllers) {
      await storageController.clearUsers();
    }
    for (const parsedUser of parsedUsers) {
      for (const storageController of this._storageControllers) {
        await storageController.setUser(parsedUser);
      }
      this._users.set(parsedUser.name, this.unparseUser(parsedUser));
      if (parsedUser.isSelected) {
        this.setCurrentUser(this.unparseUser(parsedUser));
      }
    }
    return this._currentUser == undefined;
  }

  /**
   * Public method to unparse parsed user. This method converts parameter array as a map
   * @param {LisioUserParsed} parsedUser - Parsed user from storage
   * @returns Retuns an unparsed user
   * @source
   */
  public unparseUser(parsedUser: LisioUserParsed): LisioUser {
    const parameterMap: Map<LisioParameterNames, LisioParameter> = new Map<
      LisioParameterNames,
      LisioParameter
    >(
      parsedUser.customParameters.map((customParameter) => [
        customParameter.name,
        LisioParameterFactory.current.buildLisioParameter(
          customParameter.name,
          customParameter.value as string | number | boolean,
        ),
      ]),
    );

    return new LisioUser(
      parsedUser.name,
      parsedUser.isSelected,
      parameterMap,
      parsedUser.profiles,
    );
  }
}

export default UserControllerStorage;