import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { FormRequestTaskRequest, GetExecuteWorkflow, ResponseDataGetExecuteWorkflow } 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 { ProcessManagementService } from '../../../services/process-management/process-management.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { Router } from '@angular/router';
import { SocketService } from '../../../services/socket.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-workflow-request-management',
    templateUrl: './workflow-request-management.component.html',
    styleUrl: './workflow-request-management.component.css',
    standalone: false
})
export class WorkflowRequestManagementComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;

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

  constructor(
    public resourcesService: ResourcesService,
    public interService: InternationalizationService,
    private _processManagementService: ProcessManagementService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _router: Router,
    private _socketService: SocketService,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.dataSource = new MatTableDataSource<GetExecuteWorkflow>();
    this.displayedColumns = [
      'ID_EJECUCION_WORKFLOW',
      'NOMBRE_WORKFLOW',
      'PROGRESO',
      'AUTOMATICO',
      'USUARIO_MODIFICA',
      'FECHA_MODIFICA',
      'ESTADO',
      'ACCIONES',
    ];
  }
  
  async ngOnInit() {
    await this.getExecuteWorkflow();

    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.getExecuteWorkflow();
      }
    });
  }
  
  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  public async getExecuteWorkflow() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._processManagementService.getExecuteWorkflow(user, line)).then(
      (responseData: ResponseDataGetExecuteWorkflow) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getExecuteWorkflow();
        }
      }
    );
    this.isLoading = false;
  }

  public async getExecuteTask(requestWorkflow: GetExecuteWorkflow) {
    this.isLoadingForm = true;
    const executeWorkflow: number = requestWorkflow.ID_EJECUCION_WORKFLOW;
    const formRequestTaskRequest: FormRequestTaskRequest = {
      ID: executeWorkflow,
      TYPE: 'NOTIFICATE'
    }
    
    const strFormRequest: string = JSON.stringify(formRequestTaskRequest);
    const encFormRequest: string = await this._encService.encrypt(strFormRequest);
    
    this._router.navigate([`/sam/GEPR/SFTR/GSFT/${encFormRequest}`]);
    this.isLoadingForm = false;
  }
}
