import {Component} from '@angular/core';
import {PagesService} from "@app/_services/pages.service";
import {AuthenticationService, ListsService} from "@app/_services";
import {Router} from "@angular/router";
import {Subscription} from "rxjs";

@Component({
  selector: 'header',
  templateUrl: 'header.component.html',
  styleUrls: ['header.component.scss']
})
export class HeaderComponent {
  public menuItems = <any>[];
  public user: any;
  public loading: boolean = false;
  public error: string = '';
  subscriptionUser: Subscription;
  showBottom = false;

  controlsSubscriptionMenu: Subscription;
  resultSubscriptionMenu: Subscription;

  constructor(
      private router: Router,
      private pagesService: PagesService,
      public authenticationService: AuthenticationService,
      private listsService: ListsService
  ) {
    this.subscriptionUser = this.authenticationService.user.subscribe(user => {
      this.user = user;
    });
  }

  ngOnInit() {
    let showSettingSite = localStorage.getItem('showSettingSite');
    if (showSettingSite === null || showSettingSite === 'no') {
      localStorage.setItem('showSettingSite', 'no');
      this.listsService.result('showSettingSite').next(false);
    }
    this.controlsSubscriptionMenu = this.listsService.controls('headerMenu').subscribe(controls => {
      this.fetchMenu();
    });
    this.resultSubscriptionMenu = this.listsService.result('headerMenu').subscribe(res => {
      this.menuItems = res?.data || [];
    });
  }

  ngOnDestroy() {
    this.subscriptionUser?.unsubscribe();
    this.controlsSubscriptionMenu?.unsubscribe();
    this.resultSubscriptionMenu?.unsubscribe();
  }


  fetchMenu() {
    let include = ['children.children.children.children','parents','children.parents'];
    this.pagesService.root({include: include.join(',')}).subscribe(res => {
      this.menuItems = res.data;
    });
  }

  settingsSite() {
    let showSettingSite = localStorage.getItem('showSettingSite');
    showSettingSite = showSettingSite === 'yes' ? 'no' : 'yes';
    localStorage.setItem('showSettingSite', showSettingSite);
    this.listsService.result('showSettingSite').next(showSettingSite==='yes');
  }

  login() {
    this.authenticationService.popup('login');
  }

  itemSelect(event:any){
    // if(!event.children?.data.length) 
    this.showBottom = false;
  }
}
