import {
  Component,
  OnDestroy,
  ViewChild,
  ChangeDetectorRef,
  AfterViewInit,
} from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { WorkflowInterface } from 'src/app/interfaces/samwf/workflow-interface';
import { WorkflowService } from 'src/app/services/samwf/workflow.service';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { ModulosInterface } from 'src/app/interfaces/samwf/modulos-interface';
import { Observable, lastValueFrom } from 'rxjs';
import { ResponseData } from 'src/app/services/validations.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { WorkflowFormComponent } from './workflow-form/workflow-form.component';
import { OnInit } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { AlertComponent } from '../resources/dialogs/alert/alert.component';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { ResourcesService } from '../../services/resources/resources.service';
import { MgadService } from '../../services/mgad/mgad.service';
import { DecimalPipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-workflow',
  templateUrl: './workflow.component.html',
  styleUrls: ['./workflow.component.css'],
})
export class WorkflowComponent implements AfterViewInit, OnDestroy {
  workflows: any[] = [];
  data_empty = false;
  obs: Observable<any> = new Observable<any>();
  public dataSource: MatTableDataSource<any>;

  public isLoading: boolean = true;
  public isLoadingForm: boolean = false;

  // ---- SmartPage ----
  public btnSmall: boolean = false;
  public card_size = 'card-size-normal mat-elevation-z8';
  loading = false;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  decimalPipe = new DecimalPipe(navigator.language);

  constructor(
    public dialog: MatDialog,
    private router: Router,
    private translate: TranslateService,
    private _samwfService: WorkflowService,
    private changeDetectorRef: ChangeDetectorRef,
    private _snackBar: MatSnackBar,
    private _resourceService: ResourcesService,
    private _mgadService: MgadService
  ) {
    this.dataSource = new MatTableDataSource();
    this.getWorkflows();
  }

  ngOnInit(): void {
    this.changeDetectorRef.detectChanges();
    this.obs = this.dataSource.connect();
  }

  ngOnDestroy() {
    if (this.dataSource) {
      this.dataSource.disconnect();
    }
  }

  updatePaginator() {
    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSource.paginator = this.paginator;
      this.paginator._intl.itemsPerPageLabel = data[0];
      this.paginator._intl.firstPageLabel = data[1];
      this.paginator._intl.lastPageLabel = data[2];
      this.paginator._intl.nextPageLabel = data[3];
      this.paginator._intl.previousPageLabel = data[4];
    });
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;

    if (window.innerWidth <= 721) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (window.innerWidth > 721) {
      this.btnSmall = false;
      this.card_size = 'card-size-normal mat-elevation-z8';
    }

    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSource.paginator = this.paginator;
      this.paginator._intl.itemsPerPageLabel = data[0];
      this.paginator._intl.firstPageLabel = data[1];
      this.paginator._intl.lastPageLabel = data[2];
      this.paginator._intl.nextPageLabel = data[3];
      this.paginator._intl.previousPageLabel = data[4];
    });
  }

  private async getWorkflows() {
    this.isLoading = true;

    await lastValueFrom(this._samwfService.getWorkflows()).then(
      (data: ResponseData) => {
        this.workflows = data.response;
        this.loading = true;
        this.dataSource.data = data.response;
        this.dataSource.data.length > 0
          ? (this.data_empty = false)
          : (this.data_empty = true);
        this.dataSource.data.length > 0
          ? (this.loading = false)
          : (this.loading = true);
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
        this.dataSource.data = [];
        this.loading = true;
        this.dataSource.data.length > 0
          ? (this.loading = false)
          : (this.loading = true);
        this.dataSource.data.length > 0
          ? (this.data_empty = false)
          : (this.data_empty = true);
      }
    );
    this.isLoading = false;
  }

  async openDialogFormWorkflows(action: string, item: any = {}) {
    this.isLoadingForm = true;

    this.loading = true;
    const sleep = (ms: number) =>
      new Promise((resolve) => setTimeout(resolve, ms));

    let modules: ModulosInterface[] = [];
    await lastValueFrom(this._samwfService.getModules()).then(
      (data: any) => {
        modules = data.response;
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );

    let forms: any[] = [];
    await lastValueFrom(this._mgadService.getFormsForWorkflow()).then(
      (data: any) => {
        forms = data.response;
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
      }
    );

    await sleep(200);

    let dataAction = {
      action: action,
      item: item,
      modules: modules,
      forms: forms,
    };

    const dialogRef = this.dialog.open(WorkflowFormComponent, {
      data: dataAction,
      width: '700px',
      disableClose: true,
    });

    dialogRef.afterClosed().subscribe((result: any) => {
      if (result) {
        if (action == 'Registrar') {
          result.id_module = result.module;
          if (result.isForm) {
            delete result.tasks;
          } else {
            delete result.fields;
            delete result.id_form;
          }
          this.registerWorkflow(result);
        } else {
          if (result.isForm) {
            result.tasks = [];
          } else {
            result.fields = [];
          }
          result.id_module = result.module;
          result.isAvailable = item.isAvailable;
          this.modifyWorkflow(result, item.id);
        }
      }
      this.isLoadingForm = false;
    });
  }

  public async alert(type: string, data: any = null) {
    this.isLoadingForm = true;
    let info: AlertData = {} as AlertData;
    switch (type) {
      case 'UPSW':
        info = {
          icon: 'warning',
          title: 'Actualizar Estado',
          description:
            data.isAvailable == true
              ? '¿Está seguro de desactivar este workflow?'
              : '¿Está seguro de activar este workflow?',
        };
        break;
      case 'UTW':
        info = {
          icon: 'warning',
          title: 'Actualizar forma de trabajo del workflow',
          description:
            data.isAvailable == true
              ? '¿Está seguro de cambiar a workflow manual?'
              : '¿Está seguro de cambiar a worlflow automatico?',
        };
        break;
    }

    const dialogRef = this.dialog.open(AlertComponent, {
      data: info,
      disableClose: true,
      width: '350px',
    });
    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        switch (type) {
          case 'UPSW':
            this.updateStateWorkflow(data);
            break;
          case 'UTW':
            this.updateTypeWorkflow(data);
            break;
        }
      }
      this.isLoadingForm = false;
    });
  }

  public async registerWorkflow(workflow: any) {
    await lastValueFrom(this._samwfService.registerWorkflow(workflow)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._snackBar.open('!Registro de workflow existoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
      }
    );
    this.getWorkflows();
  }

  public async modifyWorkflow(workflow: WorkflowInterface, idW: number) {
    await lastValueFrom(this._samwfService.updateWorkflow(workflow, idW)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._snackBar.open('!Modificación de workflow existoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
      }
    );
    this.getWorkflows();
  }

  public async updateStateWorkflow(item: any) {
    await lastValueFrom(this._samwfService.updateStateWorkflow(item.id)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this.ngOnInit();
          this._snackBar.open('!Modificación de estado existoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
      }
    );
    this.getWorkflows();
  }

  public async updateTypeWorkflow(item: any) {
    await lastValueFrom(this._samwfService.updateTypeWorkflow(item.id)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this.ngOnInit();
          this._snackBar.open(
            '!Modificación de tipo de worklow existoso!',
            'Cerrar',
            {
              duration: 3000,
            }
          );
        }
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
      }
    );
    this.getWorkflows();
  }

  detailWorkflow(item: any) {
    this.router.navigate(['sam/workflow', item.id]);
  }

  versionsHistory(item: any) {
    this.router.navigate(['sam/workflow/versions-history', item.id]);
  }

  public applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  public onResize(event: any) {
    if (event.target.innerWidth <= 721) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (event.target.innerWidth > 721) {
      this.btnSmall = false;
      this.card_size = 'card-size-normal mat-elevation-z8';
    }
  }
}
