import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { availableFiles } from '../../../../../environments/environment.prod';
import { ResourcesService } from '../../../../services/resources.service';
import { TempFileInfo } from '../../../../interfaces/temp-file-info.interface';
import { lastValueFrom } from 'rxjs';
import { GdelService } from '../../../../services/gdel.service';
import { MatStepper } from '@angular/material/stepper';
import { AddCloseActivityComponent } from './add-close-activity/add-close-activity.component';
import { EncService } from '../../../../services/enc.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

export interface CloseActivity{
  id: string;
  value: string;
}
@Component({
    selector: 'app-close-no-measures-order',
    templateUrl: './close-no-measures-order.component.html',
    styleUrl: './close-no-measures-order.component.css',
    standalone: false
})
export class CloseNoMeasuresOrderComponent implements OnInit {
  idOrder: string;
  attached: TempFileInfo[];
  attachedURL: string[];
  tempAttached: TempFileInfo | null;
  tempAttachedURL: string | null;
  loadingTemp: boolean;
  imageIndex: number;
  deleteFilesDisabled: boolean;
  activities: CloseActivity[];
  selectedIndexStepper: number;

  @ViewChild("stepper") stepper!: MatStepper;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _resourcesService: ResourcesService,
    private _gdelService: GdelService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<CloseNoMeasuresOrderComponent>,
  ) {
    this.idOrder = '';
    this.attached = [];
    this.attachedURL = [];
    this.tempAttached = null;
    this.tempAttachedURL = null;
    this.loadingTemp = false;
    this.imageIndex = 0;
    this.deleteFilesDisabled = false;
    this.activities = [];
    this.selectedIndexStepper = 0;
  }

  ngOnInit(): void {
    this.idOrder = this._data.idOrder;
  }

  checkFile(event: any){
    let fileTypes = availableFiles;
    let sizes = Object.keys(fileTypes);
    let extensions = Object.values(fileTypes);
    let maxSizeMB = 0;

    let extArr = event.target.files[0].name.split(".").reverse();
    let extStr = extArr[0];
    let validImages = ['png', 'jpg', 'gif', "bmp", "tiff", "svg"];

    if(!validImages.includes(extStr)){
      this._resourcesService.openSnackBar("El archivo seleccionado no es una imagen.");
      return;
    }

    let i = 0;
    extensions.forEach(ext => {
      let size = parseInt(sizes[i]);

      if(ext.includes(extStr)) maxSizeMB = size;
      i++;
    });

    if(maxSizeMB == 0){
      this._resourcesService.openSnackBar(`Los archivos ${extStr} no están soportados`);
    }else{
      let maxFileSize = 1048576 * maxSizeMB;
      let fileSize = event.target.files[0].size;

      if(fileSize > maxFileSize){
        this._resourcesService.openSnackBar(`El tamaño del archivo supera el límite de ${maxSizeMB} MB`);
      }else{
        let alreadyAttached = false;
        this.attached.forEach(file => {
          alreadyAttached = file.name == event.target.files[0].name && file.size == this._resourcesService.formatBytes(event.target.files[0].size);
        });

        if(alreadyAttached){
          this._resourcesService.openSnackBar("El archivo seleccionado ya fue adjuntado.");
        }else{
          this.uploadTmp(event.target.files[0]);
        }
      }
    }
  }

  async uploadTmp(fileData: any){
    try{
      this.loadingTemp = true;

      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('file', fileData);
      formData.append('id_user', idUser!);
      formData.append('linea', "1");

      let response = await lastValueFrom(this._gdelService.uploadTempFile(formData));

      if(response.error){
        this._resourcesService.openSnackBar(response.msg);
        this.loadingTemp = false;
      }else{
        let uploadedFile: TempFileInfo = {
          id: response.response.idArchivo,
          name: fileData.name,
          size: this._resourcesService.formatBytes(fileData.size),
          type: 'Nuevo',
        };

        let publicURL = await lastValueFrom(this._gdelService.getPublicTempDocumentUrl(response.response.idArchivo, idUser, 1));

        this.tempAttached = uploadedFile;
        this.tempAttachedURL = publicURL.response.public_uri;
        this.loadingTemp = false;
      }
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.loadingTemp = false;
    }
  }

  async deletePreview(){
    try{
      this._resourcesService.openSnackBar('Eliminando imagen de vista previa...');

      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_file', this.tempAttached!.id);

      await lastValueFrom(this._gdelService.deleteTempFile(formData));
      
      this._resourcesService.openSnackBar('Vista previa eliminada correctamente.');
      this.tempAttached = null;
      this.tempAttachedURL = null;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  savePreviewInEvidences(){
    let attachedFilt = this.attached.filter(item => item.name == this.tempAttached!.name);
    if(attachedFilt.length > 0){
      this._resourcesService.openSnackBar(`El archivo ${this.tempAttached!.name} ya fue adjuntado.`);
      return;
    }

    this.attached.push(this.tempAttached!);
    this.attachedURL.push(this.tempAttachedURL!);

    this.tempAttached = null;
    this.tempAttachedURL = null;
  }

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

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

  async deleteFile(id: string, type: string){
    try{
      if(this.deleteFilesDisabled == false){
        this.deleteFilesDisabled = true;

        let idUser = localStorage.getItem('idusuario');
        await lastValueFrom(this._gdelService.deleteTempFile({
          'id_user': idUser!,
          'id_file': id,
          'linea': 1,
        }));
  
        let attachedAux: TempFileInfo[] = [];
        let indexAux = 0;
        let indexDel = 0;

        this.attached.forEach(item => {
          if(item.id != id){
            attachedAux.push(item);
            indexDel = indexAux - 1;
          }

          indexAux++;
        });

        let urlDel = this.attachedURL[indexDel];
        let attachedURLAux: string[] = [];

        this.attachedURL.forEach(item => {
          if(item != urlDel){
            attachedURLAux.push(item);
          }
        });
  
        this.deleteFilesDisabled = false;
        this.attached = attachedAux;
        this.attachedURL = attachedURLAux;
        this.imageIndex = 0;
      }
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado. 11');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado. 12');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async closeDialog(){
    let imagesJson = JSON.stringify(this.attached);
    console.log(imagesJson);
  }

  openAddNewActivity(action: string, idActivity: string | null = null){
    let activityVal: string | undefined = undefined;
    if(action == 'edit'){
      let activityFilt = this.activities.filter(item => item.id == idActivity);
      if(activityFilt.length > 0){
        activityVal = activityFilt[0].value;
      }
    }
    
    let dialogRef = this._dialog.open(AddCloseActivityComponent, {
      width: '420px',
      maxWidth: '420px',
      disableClose: true,
      data: {
        activity: activityVal,
      }
    });

    dialogRef.afterClosed().subscribe(async (res) => {
      if(res != null && res != undefined && res != ''){
        if(action == 'new'){
          let now = new Date();
          let nowTimestamp = `${now.getTime()}`;
          let activityID = await this._encService.encrypt(nowTimestamp);
          let activityObj: CloseActivity = {
            id: activityID,
            value: res
          };
  
          this.activities.push(activityObj);
        }else{
          let activityFilt = this.activities.filter(item => item.id == idActivity);
          if(activityFilt.length > 0){
            activityFilt[0].value = res;
          }
        }
      }
    });
  }

  deleteCloseActivity(idActivity: string){
    let activitiesAux: CloseActivity[] = [];
    for(const activity of this.activities){
      if(activity.id != idActivity){
        activitiesAux.push(activity);
      }
    }

    this.activities = activitiesAux;
  }

  selectionChange(event: any){
    if(event.selectedIndex == 1 && this.activities.length <= 0){
      this._resourcesService.openSnackBar('Aún no se ha registrado ninguna actividad.');
      setTimeout(() => this.stepper.previous(), 1);
    }else if(event.selectedIndex == 2 && this.activities.length <= 0 && this.attached.length <= 0){
      this._resourcesService.openSnackBar('Aún no se ha registrado ninguna actividad.');
      setTimeout(() => this.stepper.selectedIndex = 0, 1);
    }else if(event.selectedIndex == 2 && this.activities.length > 0 && this.attached.length <= 0){
      this._resourcesService.openSnackBar('Aún no se ha registrado ninguna evidencia.');
      setTimeout(() => {
        this.stepper.selectedIndex = 0;
        this.stepper.next();
      }, 1);
    }
  }

  drop(event: CdkDragDrop<CloseActivity[]>) {
    moveItemInArray(this.activities, event.previousIndex, event.currentIndex);
  }

  async closeOrder(){
    let activitiesStr = JSON.stringify(this.activities);
    let evidenceStr = JSON.stringify(this.attached);
    let activitiesEnc = await this._encService.encrypt(activitiesStr);
    let evidenceEnc = await this._encService.encrypt(evidenceStr);
    
    let closeDataObj = {
      activities: activitiesEnc,
      evidence: evidenceEnc,
    };

    let closeDataStr = JSON.stringify(closeDataObj);
    let closeDataEnc = await this._encService.encrypt(closeDataStr);

    this._dialogRef.close(closeDataEnc);
  }
}
