import { DomTools } from './domtools.classes.domtools.js';
import * as plugins from './domtools.plugins.js';

export class ThemeManager {
  public domtoolsRef: DomTools;

  public goBrightBoolean = false;
  public preferredColorSchemeMediaMatch = window.matchMedia('(prefers-color-scheme: light)');

  public themeObservable = new plugins.smartrx.rxjs.ReplaySubject<boolean>(1);

  constructor(domtoolsRefArg: DomTools) {
    this.domtoolsRef = domtoolsRefArg;

    // lets care
    this.goBrightBoolean = this.preferredColorSchemeMediaMatch.matches;
    this.preferredColorSchemeMediaMatch.addEventListener('change', (eventArg) => {
      this.goBrightBoolean = eventArg.matches;
      this.updateAllConnectedElements();
    });
    this.updateAllConnectedElements();
  }

  public async enableAutomaticGlobalThemeChange() {
    if (document.body && document.body.style) {
      this.themeObservable.subscribe({
        next: (goBright) => {
          document.body.style.background = goBright ? '#fff' : '#000';
        }
      });
    }
  }

  private async updateAllConnectedElements() {
    this.themeObservable.next(this.goBrightBoolean);
  }

  /**
   * set the theme of the website to bright
   */
  public goBright() {
    this.goBrightBoolean = true;
    this.updateAllConnectedElements();
  }

  /**
   * set the theme of the website to dark
   */
  public goDark() {
    this.goBrightBoolean = false;
    this.updateAllConnectedElements();
  }

  /**
   * simply toggle between bright and dark
   */
  public toggleDarkBright() {
    this.goBrightBoolean = !this.goBrightBoolean;
    this.updateAllConnectedElements();
  }
}
