import { BehaviorSubject } from 'rxjs'
import { AppSettings, AppThemes } from '../models/AppSettings'

export class AppSettingsService {
  public defaultSettings: AppSettings = {
    persistSelectedTheme: true,
    selectedTheme: AppThemes.light
  }
  public settings = new BehaviorSubject<AppSettings>(this.defaultSettings)

  constructor() {
    this.restoreAppSettings()
  }

  /**
   * Restore app settings from the local storage
   */
  restoreAppSettings() {
    try {
      const serializedSettings = localStorage.getItem('app-settings')

      if (serializedSettings) {
        const settings = JSON.parse(serializedSettings)

        this.setAppSettings(settings)
      } else {
        console.info(
          'No app settings stored in the localStorage, we will set to default values.'
        )
      }
    } catch (err) {
      console.warn('Error restoring settings from local storgae.', err)
    }
  }

  /**
   * Save app settings to the local storage
   */
  storeAppSettings() {
    localStorage.setItem('app-settings', JSON.stringify(this.settings.value))
  }

  /**
   * Function used in the app to update global settings object
   *
   * @param appSettings contains properties that should be updated in settings
   */
  setAppSettings(appSettings: Partial<AppSettings>) {
    this.settings.next({
      ...this.settings.value,
      ...appSettings
    })

    this.storeAppSettings()
  }
}
