import { Component, OnInit } from '@angular/core';
import { ArborescenceCalendarListItem, ArborescenceCalendarListResponse } from '../../../interfaces/equipment-management.interface';
import { MatTreeNestedDataSource } from '@angular/material/tree';
import { NestedTreeControl } from '@angular/cdk/tree';
import { EquipmentManagementService } from '../../../services/equipment-management.service';
import { EncService } from '../../../services/enc.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-arborescence-calendar',
    templateUrl: './arborescence-calendar.component.html',
    styleUrl: './arborescence-calendar.component.css',
    standalone: false
})
export class ArborescenceCalendarComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  selected: Date | null;

  arborescence: ArborescenceCalendarListItem[];
  dataSource: MatTreeNestedDataSource<ArborescenceCalendarListItem>;

  treeControl = new NestedTreeControl<ArborescenceCalendarListItem>(node => node.HIJOS);

  constructor(
    private _equipmentManagementService: EquipmentManagementService,
    private _encService: EncService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.selected = null;

    this.arborescence = [];
    this.dataSource = new MatTreeNestedDataSource();
  }

  ngOnInit(): void {
    this.selected = new Date();
    this.getArborescence();
  }

  async getArborescence(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let year = this.selected!.getFullYear();
      let month = this.selected!.getMonth() + 1;
      let day = this.selected!.getDate();

      let arborescence: ArborescenceCalendarListResponse = await lastValueFrom(this._equipmentManagementService.arborescenceConsultByDate(
        `${year}-${month}-${day}`,
        idUser,
        1
      ));

      this.hasError = arborescence.error;
      this.errorStr = arborescence.msg;

      if(!this.hasError){
        let arborescenceArr: ArborescenceCalendarListItem[] = [];
        for(const arborescenceItem of arborescence.response){
          let elementDec = await this._encService.decrypt(arborescenceItem.ELEMENTO);
          let processedChildren = await this.processArborescenceChildren(arborescenceItem.HIJOS);

          arborescenceItem.ELEMENTO = elementDec;
          arborescenceItem.HIJOS = processedChildren;

          arborescenceArr.push(arborescenceItem);
        }

        this.arborescence = arborescenceArr;
        this.dataSource.data = this.arborescence;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  private async processArborescenceChildren(children: ArborescenceCalendarListItem[]): Promise<ArborescenceCalendarListItem[]>{
    let childrenFn: ArborescenceCalendarListItem[] = [];
    for(const child of children){
      let elementDec = await this._encService.decrypt(child.ELEMENTO);
      let processedChildren = await this.processArborescenceChildren(child.HIJOS);

      child.ELEMENTO = elementDec;
      child.HIJOS = processedChildren;

      childrenFn.push(child);
    }

    return childrenFn;
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  updateArborescenceTree(){
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.getArborescence();
  }

  hasChild = (_: number, node: ArborescenceCalendarListItem) => !!node.HIJOS && node.HIJOS.length > 0;
}
