import { Component, Input, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { EquipmentDetails } from 'src/app/interfaces/equipment-management.interface';
import { CodesHistoryComponent } from '../codes-history/codes-history.component';
import { EquipmentDocumentsComponent } from '../equipment-documents/equipment-documents.component';
import { EquipmentMaintenancePlainsComponent } from '../equipment-maintenance-plains/equipment-maintenance-plains.component';

@Component({
  selector: 'app-equipment-details',
  templateUrl: './equipment-details.component.html',
  styleUrls: ['./equipment-details.component.css']
})
export class EquipmentDetailsComponent implements OnInit {
  @Input() equipment: EquipmentDetails | null;

  images: string[];
  imageIndex: number;
  screenWidth: number;

  constructor(
    private _matIconRegistry: MatIconRegistry,
    private _domSanitizer: DomSanitizer,
    private _dialog: MatDialog,
  ){
    this._matIconRegistry.addSvgIcon(
      'xls',
      this._domSanitizer.bypassSecurityTrustResourceUrl(window.location.origin + "/assets/img/custom_icons/xls_1.svg")
    );
    this.equipment = null;
    this.images = [];
    this.imageIndex = 0;
    this.screenWidth = window.innerWidth;
  }

  ngOnInit(): void {
    this.images = this.equipment?.GALERIA_IMAGENES as string[];
  }

  onResize(){
    this.screenWidth = window.innerWidth;
  }

  forward(){
    let index = this.imageIndex + 1;
    if(index > this.images.length - 1){
      this.imageIndex = 0
    }else{
      this.imageIndex = index;
    }
  }

  backward(){
    let index = this.imageIndex - 1;
    if(index < 0){
      this.imageIndex = this.images.length - 1;
    }else{
      this.imageIndex = index;
    }
  }

  openCodesHistory(){
    this._dialog.open(CodesHistoryComponent, {
      width: '520px',
      data: {
        equipment: `${this.equipment?.CODIGO} - ${this.equipment?.TIPO_EQUIPAMIENTO} - ${this.equipment?.MODELO} (${this.equipment?.ID_EQUIPAMIENTO})`,
        history: this.equipment?.HISTORIAL_CODIGOS,
      }
    })
  }

  openDocumentsList(){
    this._dialog.open(EquipmentDocumentsComponent, {
      width: '520px',
      data: {
        equipment: `${this.equipment?.CODIGO} - ${this.equipment?.TIPO_EQUIPAMIENTO} - ${this.equipment?.MODELO} (${this.equipment?.ID_EQUIPAMIENTO})`,
        documents: this.equipment?.DOCUMENTOS
      }
    });
  }

  openMaintenancePlans(){
    this._dialog.open(EquipmentMaintenancePlainsComponent, {
      width: '720px',
      data: {
        equipment: this.equipment!,
      }
    })
  }
}
