import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { FormRequestTaskRequest, GetExecuteTask, ResponseDataGetExecuteTask } from '../../../../interfaces/process-managementv/workflow-management.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from '../../../../services/resources.service';
import { InternationalizationService } from '../../../../services/internationalization/internationalization.service';
import { ActivatedRoute } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { SocketService } from '../../../../services/socket.service';
import { ProcessManagementService } from '../../../../services/process-management/process-management.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { ChangeRequestWorkflowComponent } from '../change-request-workflow/change-request-workflow.component';
import { HistoryNotificateTaskComponent } from '../history-notificate-task/history-notificate-task.component';

@Component({
    selector: 'app-task-request-from-workflow',
    templateUrl: './task-request-from-workflow.component.html',
    styleUrl: './task-request-from-workflow.component.css',
    standalone: false
})
export class TaskRequestFromWorkflowComponent implements OnInit {
  public idExecute!: number;
  private typeExecute!: 'VALIDATE' | 'NOTIFICATE';

  public isLoading: boolean;
  public isLoadingForm: boolean;

  public dataSource: MatTableDataSource<GetExecuteTask>;
  public displayedColumns: Array<string>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    public resourcesService: ResourcesService,
    public interService: InternationalizationService,
    private _activatedRoute: ActivatedRoute,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _socketService: SocketService,
    private _processManagementService: ProcessManagementService,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.dataSource = new MatTableDataSource<GetExecuteTask>();
    this.displayedColumns = [
      'ID_EJECUCION_TAREA',
      'NOMBRE_TAREA',
      'USUARIO_RESPONSABLE',
      'PROGRESO',
      'FECHA_MODIFICA',
      'USUARIO_MODIFICA',
      'ESTADO',
      'ACCIONES',
    ];
  }
  
  async ngOnInit() {
    this.isLoading = true;
    await this.getDataForm();
    this.isLoading = false;


    this._socketService.notificationPublished().subscribe(async (notificationData) => {
      let audienceStr: string = await this._encService.decrypt(notificationData.audience);
      let audienceArr: Array<string> = JSON.parse(audienceStr);

      const encUserActive: string = this.resourcesService.getUser();
      const idUserActive: string = await this._encService.decrypt(encUserActive);
      
      if (audienceArr.includes(idUserActive)) {
        await this.getExecuteTask();
      }
    });
  }

  public async getDataForm() {
    const getForm: string | null = this._activatedRoute.snapshot.paramMap.get('form');
    if (getForm !== null) {
      const decForm: string = await this._encService.decrypt(getForm);
      const formRequest: FormRequestTaskRequest = JSON.parse(decForm);

      this.idExecute = formRequest.ID;
      this.typeExecute = formRequest.TYPE;

      await this.getExecuteTask();
    } else {
      this.resourcesService.openSnackBar(`No se pudo obtener la información de la ejecución.`);
      this.resourcesService.goBack();
    }
  }

  public async getExecuteTask() {
    this.isLoading = true;
    const encExecute: string = await this._encService.encrypt(this.idExecute.toString());
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._processManagementService.getExecuteTask(encExecute, user, line)).then(
      (responseData: ResponseDataGetExecuteTask) => {
        if (!responseData.error) {
          let arrTemp: GetExecuteTask[] = []
          for (const element of responseData.response) {
            arrTemp.push({
              ID_EJECUCION_WORKFLOW: element.ID_EJECUCION_WORKFLOW,
              ID_EJECUCION_TAREA: element.ID_EJECUCION_TAREA,
              NOMBRE_TAREA: element.NOMBRE_TAREA,
              USUARIO_RESPONSABLE: element.USUARIO_RESPONSABLE,
              NOMBRE_PROCESO: element.NOMBRE_PROCESO,
              PROGRESO: parseFloat(this.resourcesService.resizeText(element.PROGRESO.toString(), 5)),
              NOMBRE_WORKFLOW: element.NOMBRE_WORKFLOW,
              INFORMACION_FORMULARIO: element.INFORMACION_FORMULARIO,
              INFORMACION_REGISTRO: element.INFORMACION_REGISTRO,
              ESTADO: element.ESTADO,
              USUARIO_MODIFICA: element.USUARIO_MODIFICA,
              FECHA_MODIFICA: element.FECHA_MODIFICA,
            })
          }
          this.dataSource.data = arrTemp;
          
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
          this.resourcesService.goBack();
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getExecuteTask();
        } else {
          this.resourcesService.goBack();
        }
      }
    );
    this.isLoading = false;
  }

  public async openExecuteTask(executeTask: GetExecuteTask) {
    this._dialog.open(ChangeRequestWorkflowComponent, {
      disableClose: true,
      data: executeTask,
      width: '450px',
      maxWidth: '450px',
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.getExecuteTask()
      }
    });
  }

  public async openHistory(executeTask: GetExecuteTask) {
    this._dialog.open(HistoryNotificateTaskComponent, {
      disableClose: true,
      data: executeTask.ID_EJECUCION_TAREA,
      width: '1400px',
      maxWidth: '1400px',
    });
  }
}
