import { Injectable } from '@angular/core';

enum ThemeType {
  compact = 'compact',
  default = 'default',
}

@Injectable({
  providedIn: 'root',
})
export class ThemeService {
  currentTheme = ThemeType.default;

  constructor() {}

  private reverseTheme(theme: string): ThemeType {
    return theme === ThemeType.compact ? ThemeType.default : ThemeType.compact;
  }

  private removeUnusedTheme(theme: ThemeType): void {
    document.documentElement.classList.remove(theme);
    const removedThemeStyle = document.getElementById(theme);
    if (removedThemeStyle) {
      document.head.removeChild(removedThemeStyle);
    }
  }

  private loadCss(href: string, id: string): Promise<Event> {
    return new Promise((resolve, reject) => {
      const style01 = document.createElement('link');
      style01.rel = 'stylesheet';
      style01.href = 'compact.css';
      style01.onload = resolve;
      style01.onerror = reject;
      document.body.after(style01);
      
      const style = document.createElement('link');
      style.rel = 'stylesheet';
      style.href = href;
      style.onload = resolve;
      style.onerror = reject;
      document.body.after(style);

      
    });
    
  }

  public loadTheme(firstLoad = true): Promise<Event> {
    //const theme = this.currentTheme;
    const theme = 'assets/style.compact';
    if (firstLoad) {
      document.documentElement.classList.add(theme);
    }
    return new Promise<Event>((resolve, reject) => {
      this.loadCss(`${theme}.css`, theme).then(
        (e) => {
          if (!firstLoad) {
            document.documentElement.classList.add(theme);
          }
          this.removeUnusedTheme(this.reverseTheme(theme));
          resolve(e);
        },
        (e) => reject(e)
      );
    });
  }

  public toggleTheme(): Promise<Event> {
    this.currentTheme = this.reverseTheme(this.currentTheme);
    return this.loadTheme(false);
  }
}
