import { SocketService } from './../../../services/socket.service';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DetailsAlertComponent } from './details-alert/details-alert.component';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MaintenanceStatusResponse } from './../../../interfaces/maintenance-status.interface';
import { BasicAlertComponent } from './../../resources/dialogs/basic-alert/basic-alert.component';
import { MatDialog } from '@angular/material/dialog';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MaintenanceHistory } from './../../../interfaces/maintenance-history.interface';
import { lastValueFrom } from 'rxjs';
import { EncService } from 'src/app/services/enc/enc.service';
import { SystemAdminService } from './../../../services/system-admin.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MaintenanceHistoryResponse } from 'src/app/interfaces/maintenance-history.interface';

@Component({
  selector: 'app-maintenance-mode',
  templateUrl: './maintenance-mode.component.html',
  styleUrls: ['./maintenance-mode.component.css']
})
export class MaintenanceModeComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  maintenanceStatus: boolean;
  errorStr: string;
  maintenanceHistory: MaintenanceHistory[];

  dataSource?: MatTableDataSource<MaintenanceHistory>;
  displayedColumns = ["ID", "USRACT", "FECACT", "USRDES", "FECDES", "ACCIONES"];

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

  public btnSmall: boolean = false;
  public txtBuscador:string;

  constructor(
    private _systemAdminService: SystemAdminService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _snackBar: MatSnackBar,
    private _socketService: SocketService,
  ) { 
    this.hasError = false;
    this.isLoading = true;
    this.maintenanceStatus = false;
    this.errorStr = "";
    this.maintenanceHistory = [];
    this.txtBuscador = '';
  }

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

  async getData(){
    try{
      let idUser = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
      let maintenanceHistory: MaintenanceHistoryResponse = await lastValueFrom(this._systemAdminService.getMaintenanceHistory(shortEnc.response.encrypted, 1));
      
      this.errorStr = maintenanceHistory.msg;
      this.hasError = maintenanceHistory.error;

      if(this.hasError){
        this.isLoading = false;
      }else{
        this.maintenanceHistory = maintenanceHistory.response;
        this.dataSource = new MatTableDataSource(this.maintenanceHistory);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;

        this.isLoading = false;
      }
    }catch(error: any){
      let msg = "";
      if(error.error == undefined){
        msg = "Ocurruió un error inesperado";
      }else if(error.error.msg == undefined){
        msg = "Ocurruió un error inesperado";
      }else{
        msg = error.error.msg;
      }

      this.errorStr = msg;
    }
  }

  async getMaintenanceStatus(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";

      let idUser = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
      let maintenanceStatus: MaintenanceStatusResponse = await lastValueFrom(this._systemAdminService.getMaintenanceStatus(shortEnc.response.encrypted, 1));

      this.hasError = maintenanceStatus.error;
      this.errorStr = maintenanceStatus.msg;
      if(this.hasError){
        this.isLoading = false;
      }else{
        this.maintenanceStatus = maintenanceStatus.response.activated;
        this.getData();
      }
    }catch(error: any){
      let msg = "";
      if(error.error == undefined){
        msg = "Ocurrió un error inesperado.";
      }else if(error.error.msg == undefined){
        msg = "Ocurrió un error inesperado.";
      }else{
        msg = error.error.msg;
      }

      this.hasError = true;
      this.errorStr = msg
    }
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  buildDate(date: string): string{
    if(date == "" || date == null || date == undefined){
      return '-';
    }

    let dateTimeArr = date.split(" ");
    let dateArr = dateTimeArr[0].split("-");
    dateArr = dateArr.reverse();

    let timeArr = dateTimeArr[1].split(":");
    let hour = timeArr[0];
    let timeStr = "";

    if(parseInt(hour) > 12){
      let hourPM = parseInt(hour) - 12 > 10 ? `${hour}` : `0${parseInt(hour) - 12}`;
      timeStr += `${hourPM}:${timeArr[1]} PM`;
    }else{
      timeStr += `${hour}:${timeArr[1]} AM`;
    }
    
    return `${dateArr.join("/")} ${timeStr}`;
  }

  openBasicAlert(msg: string, type: string){
    let title = "";
    if(type == "d") title = "Duración del mantenimiento";
    if(type == "m") title = "Motivo de la intervención";
    if(type == "j") title = "Justificación de la solución";

    this._dialog.open(BasicAlertComponent, {
      data: {
        title: title,
        body: msg,
      }
    });
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    })
  }

  changeMaintenanceStatus(){
    if(this.maintenanceStatus){
      console.log(this.maintenanceStatus);
    }else{
      let title = "Motivo de la activación";
      let body = "Por favor ingrese los motivos para realizar la activación";

      let dialogRef = this._dialog.open(DetailsAlertComponent, {
        data: {
          title: title,
          body: body,
        },
        disableClose: true,
      });

      dialogRef.afterClosed().subscribe(result => {
        if(result != false){
          this.confirmChange(result);
        }
      })
    }
  }

  async confirmChange(motives: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let confirmData: AlertData = {
        icon: 'warning',
        title: 'Confirmar acción',
        description: '¿Está seguro de activar el modo mantenimiento?',
        description2: 'Esta acción deshabilitará el acceso al SAM a todos los usuarios que no tengan habilitada la función del "Modo mantenimiento" en su perfil y les dará un tiempo máximo de 5 minutos para cerrar sesión a partir de la confirmación de la acción.'
      };

      let confirmRef = this._dialog.open(AlertComponent, {
        data: confirmData
      });

      confirmRef.afterClosed().subscribe(async (res) => {
        if(res == true){
          const formMaintenance = new FormData();
          formMaintenance.append('id_user', idUser!);
          formMaintenance.append('linea', '1');
          formMaintenance.append('motivos', motives);
          
          await lastValueFrom(this._systemAdminService.activateMaintenanceMode(formMaintenance));

          this._socketService.maintenanceActivated();
        }
      });
    }catch(error: any){
      let msg = "";
      if(error.error == undefined){
        msg = "Ocurrió un error inesperado.";
      }else if(error.error.msg == undefined){
        msg = "Ocurrió un error inesperado.";
      }else{
        msg = error.error.msg;
      }

      this.openSnackBar(msg);
    }
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }
}
