import { ApiError } from "@api-client/core/build/browser.js";
import { IListState } from "./State.js";

/**
 * A class that serializes and deserializes the pagination cursor.
 */
export class Cursor {
  /**
   * Reads the cursor received from the client by decrypting its contents.
   * It throws an error when the cursor is invalid
   */
  async decodeCursor(cursor: string): Promise<IListState> {
    let result: IListState;
    try {
      const decoded = window.atob(cursor);
      result = JSON.parse(decoded);
    } catch (e) {
      throw new ApiError(`Invalid page cursor.`, 400);
    }
    return result;
  }

  /**
   * Encodes the state into a cursor.
   * @param state The list state.
   * @returns The encoded (base64) cursor.
   */
  async encodeCursor(state: object): Promise<string> {
    const str = JSON.stringify(state);
    return window.btoa(str);
  }
}
