import tauriSessionStorage from '../tauri/tauri-session';

/** 'competition-topic'---竞赛主观题; 'judge-topic'---判断题; 'choice-topic'---选择题; 'real-time-topic'---实时主观题; 'work'-作业 */
export type TimerType = 'choice-topic' | 'competition-topic' | 'judge-topic' | 'pk-select' | 'pk-subjectivity' | 'pk-type-in' | 'real-time-topic' | 'work';
/**
 * 存储计时开始时间
 */
export class PageTimetorage {
  private readonly key = 'SRXY-HDKT-PAGE-TIMER';
  /**
   * 得到开始时间
   * @param type - 类型
   */
  public async get(type: TimerType): Promise<number | null> {
    const _key = `${this.key}-${type}`;
    let time: string | null = null;
    try {
      time = ((await tauriSessionStorage.get(_key)) as string) || null;
    } catch (error: any) {
      console.log('error====', error);
    }

    const timestamp = time === null || isNaN(Number(time)) ? null : Number(time);
    if (timestamp === null) {
      await this.set(type, new Date().getTime());
    }

    return timestamp;
  }
  /**
   * 设置开始时间
   * @param type - 类型
   * @param time - 时间戳 (单位: 毫秒)
   */
  public async set(type: TimerType, time: number = new Date().getTime()) {
    const _key = `${this.key}-${type}`;
    try {
      await tauriSessionStorage.set(_key, String(time));
    } catch (error: any) {
      console.log('error====', error);
    }
  }
}
