File size: 2,061 Bytes
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import Dexie, { Table } from "dexie";
import { IConfig, DEFAULT_CONFIG } from "./types";

export class ConfigManager extends Dexie {
  configs!: Table<IConfig>;
  private static instance: ConfigManager;
  private currentConfig: IConfig | null = null;

  private constructor() {
    super("configs");
    this.version(1).stores({
      configs: "id, createdAt, updatedAt",
    });
    this.initialize();
  }

  public static getInstance(): ConfigManager {
    if (!ConfigManager.instance) {
      ConfigManager.instance = new ConfigManager();
    }
    return ConfigManager.instance;
  }

  async initialize() {
    const configs = await this.configs.toArray();
    if (configs.length === 0) {
      // Create default config if none exists
      const defaultConfig: IConfig = {
        ...DEFAULT_CONFIG,
        id: crypto.randomUUID(),
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      await this.configs.add(defaultConfig);
      this.currentConfig = defaultConfig;
    } else {
      // Use the most recently updated config
      this.currentConfig = configs.sort((a, b) => b.updatedAt - a.updatedAt)[0];
    }
    return this.currentConfig;
  }

  async getConfig(): Promise<IConfig> {
    if (!this.currentConfig) {
      await this.initialize();
    }
    return this.currentConfig!;
  }

  async updateConfig(updates: Partial<Omit<IConfig, 'id' | 'createdAt' | 'updatedAt'>>): Promise<IConfig> {
    const current = await this.getConfig();
    const updatedConfig: IConfig = {
      ...current,
      ...updates,
      updatedAt: Date.now(),
    };
    
    await this.configs.put(updatedConfig);
    this.currentConfig = updatedConfig;
    return updatedConfig;
  }

  async resetToDefaults(): Promise<IConfig> {
    const current = await this.getConfig();
    const resetConfig: IConfig = {
      ...DEFAULT_CONFIG,
      id: current.id,
      createdAt: current.createdAt,
      updatedAt: Date.now(),
    };
    
    await this.configs.put(resetConfig);
    this.currentConfig = resetConfig;
    return resetConfig;
  }
}