import { Component, ViewChild, AfterViewInit, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { WorkflowService } from 'src/app/services/samwf/workflow.service';
import { filter } from '@syncfusion/ej2/maps';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
  selector: 'app-workflow-history-notification',
  templateUrl: './workflow-history-notification.component.html',
  styleUrls: ['./workflow-history-notification.component.css'],
})
export class WorkflowHistoryNotificationComponent implements OnInit {
  loading: Boolean = false;
  notifications: any[] = [];
  data_empty = false;
  filter_empty = false;

  displayedColumns: string[] = ['module', 'date_send', 'task'];

  minDate: Date;
  maxDate: Date;
  modules: any[] = [];
  filterSendDate: any;
  filterModule: any;

  dataSource = new MatTableDataSource<any>(this.notifications);

  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(
    public dialog: MatDialog,
    private router: Router,
    private translate: TranslateService,
    private _samwfService: WorkflowService,
    private _snackBar: MatSnackBar
  ) {
    const currentYear = new Date().getFullYear();
    this.minDate = new Date(currentYear - 2, 0, 0);
    this.maxDate = new Date(currentYear + 1, 0, 0);
    translate.setDefaultLang('es');
  }

  ngAfterViewInit(): void {
    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];
    });

    this.dataSource.filterPredicate = function (data, filter: string): boolean {
      return (
        data.content.date.toString().toLowerCase().includes(filter) ||
        data.content.workflow.toString().toLowerCase().includes(filter) ||
        data.content.task.toLowerCase().includes(filter)
      );
    };
  }

  applyFilter(filterValue: any) {
    this.dataSource.filter = filterValue.target.value.trim().toLowerCase();
  }

  ngOnInit(): void {
    this.getNotifications();
  }

  clearFilter() {
    this.ngOnInit();
    this.data_empty = false;
    this.filter_empty = false;
  }

  backToWorkflows() {
    this.router.navigate(['workflow']);
  }

  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];
    });
  }

  filter() {
    let arrFilter: any[] = this.notifications;
    let dateAux: string = '';
    let arrAux: any[] = [];
    if (this.filterSendDate != undefined) {
      dateAux = this.formatDate(this.filterSendDate);
      for (let index = 0; index < arrFilter.length; index++) {
        if (arrFilter[index].created_at == dateAux) {
          arrAux.push(arrFilter[index]);
        }
      }
      this.filterModuleFunction(arrAux);
    } else {
      this.filterModuleFunction(arrFilter);
    }
  }

  filterModuleFunction(arrFilter: any[]) {
    let arrAux: any[] = [];
    if (this.filterModule != undefined && arrFilter.length > 0) {
      for (let index = 0; index < arrFilter.length; index++) {
        if (arrFilter[index].module == this.filterModule) {
          arrAux.push(arrFilter[index]);
        }
      }
      this.dataSource.data = arrAux;
      this.dataSource.data.length > 0
        ? (this.filter_empty = false)
        : (this.filter_empty = true);
    } else {
      this.dataSource.data = arrAux;
      this.dataSource.data.length > 0
        ? (this.filter_empty = false)
        : (this.filter_empty = true);
    }
  }

  private formatDate(date: Date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
  }

  private async getNotifications() {
    await lastValueFrom(this._samwfService.getNotificationsByUser(1)).then(
      (data: any) => {
        this.dataSource.data = data.filter((object: any) => {
          object.content.date = object.content.date.slice(0, 10);
          return object;
        });

        this.notifications = data.filter((object: any) => {
          object.content.date = object.content.date.slice(0, 10);
          return object;
        });

        this.dataSource.data.length > 0
          ? (this.data_empty = false)
          : (this.data_empty = true);
      },
      (error: any) => {
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );

    await lastValueFrom(this._samwfService.getModules()).then(
      (data: any) => {
        this.modules = data;
      },
      (error: any) => {
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
  }
}
