import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { AppThemeConfig } from 'src/theme/app-theme-config';
import { App } from './App';

@Injectable({
  providedIn: 'root'
})
export class SettingsService {

  /**
   * 主题中转对象
   */
  private theme: BehaviorSubject <string>;
  
  constructor(private $app:App) { 
    let tempTheme:any;
    let appTheme = localStorage.getItem('app-theme');
    if (appTheme) {
      tempTheme = appTheme;
    } else {
      tempTheme = 'default';
    }
    if(!this.theme){
      this.theme = new BehaviorSubject(tempTheme);
    }
    this.setActiveTheme(tempTheme);
  }

  /**
   * 设置主题
   * @param val  主题标识 
   */
  public setActiveTheme(val){
    localStorage.setItem('app-theme',val);
    document.getElementsByTagName('html')[0].className = val;
    this.theme.next(val);
  }

  /**
   * 监听主题变化
   */
  public getActiveTheme() {
      return this.theme.asObservable();
  }

  /**
   * 切换主题
   */
  public async changeTheme(){
    let appTheme = localStorage.getItem('app-theme');
    const result: string = await this.$app.openActionSheet({ items: AppThemeConfig });
    if (!Object.is(result, appTheme)) {
     this.setActiveTheme(result);
    }
  }

}
