import {ref, Ref} from "vue"; import {Setting} from "../types"; import {CommonAPI} from "../api"; export default class SettingMapper { private static instance: SettingMapper; private moduleMap = new Map>>(); public static async loadSetting(map: Record): Promise { const result = await CommonAPI.settingMap(map); this.appendSettingMap(result); } public static appendSettingMap(result: Map>): void { for (const [module, settingMap] of result) { for (const [key, setting] of settingMap) { this.setValue(module, key, setting); } } } public static createModule(module: string): Map> { const instance = this.getInstance(); const moduleVal = instance.moduleMap.get(module); if (moduleVal) { return moduleVal; } const created = new Map>(); instance.moduleMap.set(module, created); return created; } public static getModule(module: string): Map> | undefined { return this.getInstance().moduleMap.get(module); } public static hasModule(module: string): boolean { return this.getInstance().moduleMap.has(module); } public static deleteModule(module: string): boolean { return this.getInstance().moduleMap.delete(module); } public static setModule(module: string, moduleVal: Map>): void { this.getInstance().moduleMap.set(module, moduleVal); } public static is(module: string, key: string): boolean { const setting = this.getValueRef(module, key).value; return !!setting.value && setting.value === "true"; } public static not(module: string, key: string): boolean { return !this.is(module, key); } public static getValue(module: string, key: string): Setting { return this.getValueRef(module, key).value; } public static setValue(module: string, key: string, setting: Setting): void { const moduleVal = this.createModule(module); const settingRef = moduleVal.get(key); if (settingRef) { settingRef.value = setting; return; } moduleVal.set(key, ref(setting)); } public static setValueRef(module: string, key: string, settingRef: Ref): void { const moduleVal = this.createModule(module); moduleVal.set(key, settingRef); } public static hasValue(module: string, key: string): boolean { return !!this.getModule(module)?.has(key); } public static deleteValue(module: string, key: string): boolean { return !!this.getModule(module)?.delete(key); } public static getValueRef(module: string, key: string): Ref { const moduleVal = this.getModule(module); if (!moduleVal) { throw new Error(`Setting module not found: ${module}`); } const valueRef = moduleVal.get(key); if (!valueRef) { throw new Error(`Setting key not found: ${module}.${key}`); } return valueRef; } public static getInstance(): SettingMapper { if (SettingMapper.instance) { return SettingMapper.instance; } return SettingMapper.instance = new SettingMapper(); } }