import { preferences } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
import { Logger } from './Logger';
import emitter from '@ohos.events.emitter';
import { EVT_KV_INIT_DONE } from '../constants/EventConstants';
import { IS_KV_STORE_INIT_FINISHED } from '../constants/AppConstants';

export class KVStore {
  private static instance: KVStore | null = null;
  private pref: preferences.Preferences | null = null;

  private constructor() {}

  // 初始化（建议在 UIAbility 的 onCreate 中调用一次）
  static async init(context: common.Context): Promise<void> {
    if (!KVStore.instance) {
      const store = new KVStore();
      // 获取 Preferences 实例必须异步等待
      store.pref = await preferences.getPreferences(context, 'cn_img_rabbit_kv_store');
      KVStore.instance = store;

      emitter.emit({ eventId: EVT_KV_INIT_DONE });
      AppStorage.setOrCreate<boolean>(IS_KV_STORE_INIT_FINISHED, true);
      Logger.info('Rabbit_KVStore', 'KVStore initialized finish.');
    }
  }

  static getInstance(): KVStore {
    if (!KVStore.instance) {
      // 抛出错误比返回 undefined 更好，能让你一眼看到是不是顺序错了
      throw new Error("Rabbit_KVStore is not initialized. Please call await KVStore.init() in Ability onCreate.");
    }
    return KVStore.instance;
  }

  // 存储数据 (模拟 MMKV put)
  async put(key: string, value: preferences.ValueType): Promise<void> {
    if (!this.pref) {
      // 如果 pref 为空，尝试重新补救（或者抛出错误方便排查）
      Logger.info('Rabbit_KVStore', `KVStore: pref is null when putting key: ${key}`);
      return;
    }
    try {
      await this.pref.put(key, value);
      await this.pref.flush(); // 持久化到磁盘
      Logger.info('Rabbit_KVStore', `KVStore: Successfully saved ${key}  ----  ${value}`);
    } catch (err) {
      Logger.info('Rabbit_KVStore', `KVStore: Save failed, error: ${JSON.stringify(err)}`);
    }
  }


  // 读取数据 (模拟 MMKV get)
  async get<T extends preferences.ValueType>(key: string, defaultValue: T): Promise<T> {
    if (this.pref) {
      const val = await this.pref.get(key, defaultValue) as T;
      Logger.info('Rabbit_KVStore', `KVStore: Fetching ${key}, value is: ${val}`);
      return val;
    }
    Logger.info('Rabbit_KVStore', `KVStore: pref is null, returning default for ${key}`);
    return defaultValue;
  }

  /**
   * 同步读取数据 (对应 Android MMKV.decodeString)
   * 必须确保 pref 已经初始化完成
   */
  getSync<T extends preferences.ValueType>(key: string, defaultValue: T): T {
    if (this.pref !== null) {
      // 使用系统提供的 getSync 接口
      return this.pref.getSync(key, defaultValue) as T;
    }
    return defaultValue;
  }

  // 删除数据
  async delete(key: string): Promise<void> {
    if (this.pref) {
      await this.pref.delete(key);
      await this.pref.flush();
    }
  }
}
