import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';

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

  arborescence: any[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _matIconRegistry: MatIconRegistry,
    private _domSanitizer: DomSanitizer,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.arborescence = [];
  }

  ngOnInit(): void {
    this.init();
  }

  async init() {
    let arborescenceDec = await this._encService.decrypt(this._data.arborescence);
    let arborescenceArr = JSON.parse(arborescenceDec);

    let levelNum = 0;
    for(const level of arborescenceArr){
      if(levelNum > 0 && levelNum <= 2){
        let graphObj = JSON.parse(level.graph);
        if(graphObj.customIcon == 'S'){
          this._matIconRegistry.addSvgIcon(
            graphObj.icon,
            this._domSanitizer.bypassSecurityTrustResourceUrl(`${window.location.origin}/assets/img/custom_icons/${graphObj.icon}.svg`)
          );
        }

        level.graph = graphObj;
      }

      levelNum++;
    }

    this.arborescence = arborescenceArr;
    this.isLoading = false;
  }
}