import { Component, OnInit } from '@angular/core';
import { NbMenuItem } from '@nebular/theme';
import { PastoralDomainService } from '../services/crudServices/pastoral-domain.service';
import { ObjectUtils } from '../utilities/object-utils';
import { CellGroupRoutingConfig } from './cell-group-routing.module';
import { first } from 'rxjs/operators';

@Component({
  selector: 'ngx-cell-group',
  templateUrl: './cell-group.component.html',
  styleUrls: ['./cell-group.component.scss']
})
export class CellGroupComponent implements OnInit {

  MENU_ITEMS = ObjectUtils.CloneValue(CellGroupRoutingConfig.MENU_ITEMS);
  constructor(
    private pastoralDomainService: PastoralDomainService
  ) {
    let subscription = pastoralDomainService.initialized.subscribe(result => {
      if (result) {
        this.initializeSideMenu();
        subscription.unsubscribe();
      }
    });
  }

  ngOnInit(): void {

  }

  private initializeSideMenu() {

    for (let i = 0; i < this.MENU_ITEMS.length; i++) {
      const item = this.MENU_ITEMS[i];
      this.checkDisplayItem(item);
    }
  }
  private checkDisplayItem(item: NbMenuItem) {
    if (item.data != undefined) {
      var group = this.pastoralDomainService.domains.find(d => d.type == item.data);
      if (!group) {
        item.hidden = true;
        return;
      }
      item.title = `${group.name}`;
      item.children.forEach(element => {
        element.link += `/${group.id}`;
      });

    } else if (item.children) {
      item.children.forEach(element => {
        this.checkDisplayItem(element);
      });
    }
  }
}
