import {
  Component,
  ViewChild,
  AfterViewInit,
  OnInit,
  ChangeDetectorRef,
} from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator, MatPaginatorIntl } 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 { MatSnackBar } from '@angular/material/snack-bar';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
  selector: 'app-workflow-history-notification',
  templateUrl: './workflow-history-notification.component.html',
  styleUrls: ['./workflow-history-notification.component.css'],
})
export class WorkflowHistoryNotificationComponent implements AfterViewInit {
  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;

  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';

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

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

    const currentYear = new Date().getFullYear();
    this.minDate = new Date(currentYear - 2, 0, 0);
    this.maxDate = new Date(currentYear + 1, 0, 0);
    translate.setDefaultLang('es');

    this.getNotifications();
  }

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

  ngOnInit(): void {}

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

  backToWorkflows() {
    this.router.navigate(['sam/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() {
    this.isLoading = true;
    await lastValueFrom(this._samwfService.getNotificationsByUser(1)).then(
      (data: any) => {
        this.dataSource.data = data.response.filter((object: any) => {
          object.content.date = object.content.date.slice(0, 10);
          return object;
        });

        this.notifications = data.response.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: HttpErrorResponse) => {
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );

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

  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';
    }
  }
}
