import {Injectable} from "@angular/core";
import {BehaviorSubject, Observable} from "rxjs";
import {ActivationStart, Router} from "@angular/router";

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

  /**
   * Set this to true when sidebar items are ready.
   */
  private openSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  /**
   *  Add hasSidebar: false on data of route config, if sidebar is not needed.
   */
  private hasSidebarSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);

  /**
   *  Add hasHeader: false on data of route config, if header is not needed.
   */
  private hasHeaderSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);

  constructor(private router: Router) {
    this.router.events.subscribe(event => {
      if (event instanceof ActivationStart) {
        let data = event.snapshot.data;
        if (this.hasSidebarSubject.value === true &&
          data['hasSidebar'] !== undefined &&
          data['hasSidebar'] === false) {
          this.setHasSidebar(false);
        } else if (this.hasSidebarSubject.value === false) {
          this.setHasSidebar(true);
        }
        if (this.hasHeaderSubject.value === true &&
          data['hasHeader'] !== undefined &&
          data['hasHeader'] === false) {
          this.setHasHeader(false);
        } else if (this.hasHeaderSubject.value === false) {
          this.setHasHeader(true);
        }
      }
    });
  }

  get open(): boolean {
    return this.openSubject.getValue();
  }

  setOpen(value: boolean) {
    this.openSubject.next(value);
  }

  get hasSidebar(): Observable<boolean> {
    return this.hasSidebarSubject.asObservable();
  }

  setHasSidebar(value: boolean) {
    this.hasSidebarSubject.next(value);
  }

  get hasHeader(): Observable<boolean> {
    return this.hasHeaderSubject.asObservable();
  }

  setHasHeader(value: boolean) {
    this.hasHeaderSubject.next(value);
  }
}
