import {Injectable} from '@angular/core';
import {CookieService} from 'ngx-cookie-service';
import {BehaviorSubject} from 'rxjs';
import {THEME_MODE} from '@custom-types/constant';

@Injectable({
  providedIn: 'root'
})
export class ThemeService {
  private readonly THEME_KEY = 'theme';

  private themeSubject: BehaviorSubject<THEME_MODE> = new BehaviorSubject<THEME_MODE>(THEME_MODE.LIGHT);
  public theme$ = this.themeSubject.asObservable();

  constructor(private cookieService: CookieService) {
    this.initializeTheme();
  }

  public initializeTheme(): void {
    const savedTheme = this.cookieService.check(this.THEME_KEY)
      ? this.cookieService.get(this.THEME_KEY)
      : THEME_MODE.DARK;
    let currentTheme: THEME_MODE;
    switch (savedTheme) {
      case THEME_MODE.DARK: {
        currentTheme = THEME_MODE.DARK;
        break;
      }
      case THEME_MODE.LIGHT:
      default: {
        currentTheme = THEME_MODE.LIGHT;
      }
    }
    this.setTheme(currentTheme);
  }

  public setTheme(themeName: THEME_MODE): void {
    this.cookieService.set(this.THEME_KEY, themeName, 365);
    document.body.className = themeName;
    this.themeSubject.next(themeName);
  }

  public toggleTheme(): THEME_MODE {
    const currentTheme = this.themeSubject.getValue();
    const newTheme = currentTheme === THEME_MODE.LIGHT ? THEME_MODE.DARK : THEME_MODE.LIGHT;
    this.setTheme(newTheme);
    return newTheme
  }
}
