import { InfoService } from './InfoService'
import { LocalStorageService } from './LocalStorageService'
import type { StorageInterface } from './StorageInterface'
import { TauriFileStorageService } from './TauriFileStorageService'

export class PersistenceService {
  private infoService: InfoService = new InfoService()
  private static instance: PersistenceService
  private storage: StorageInterface
  private constructor() {
    this.storage = this.infoService.tauri
      ? new TauriFileStorageService()
      : new LocalStorageService()
  }

  static getInstance(): PersistenceService {
    if (!PersistenceService.instance) {
      PersistenceService.instance = new PersistenceService()
    }
    return PersistenceService.instance
  }

  async saveToken(token: string) {
    await this.storage.saveUserDataText('token', token)
  }

  async saveRefreshToken(refreshToken: string) {
    await this.storage.saveUserDataText('refreshToken', refreshToken)
  }

  async readToken(): Promise<string> {
    try {
      const token = await this.storage.readUserDataText('token')
      return token
    } catch (error) {
      console.error(error)
      return ''
    }
  }

  async readRefreshToken() {
    try {
      const refreshToken = await this.storage.readUserDataText('refreshToken')
      return refreshToken
    } catch (error) {
      console.error(error)
      return ''
    }
  }

  async clearTokens() {
    await this.storage.deleteUserDataText('token')
    await this.storage.deleteUserDataText('refreshToken')
  }

  async saveConfig(config: any) {
    await this.storage.saveConfigData(config)
  }

  async readConfig() {
    const config = await this.storage.readConfigData()
    return config
  }
}
