import { Component, OnInit, ViewChild } from '@angular/core';
import { MaintenanceHistory, MaintenanceHistoryResponse } from '../../../interfaces/maintenance-history.interface';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { SystemAdminService } from '../../../services/system-admin.service';
import { EncService } from '../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { SocketService } from '../../../services/socket.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { Router } from '@angular/router';
import { ResourcesService } from '../../../services/resources.service';
import { FunctionsService } from '../../../services/functions.service';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { MaintenanceStatusResponse } from '../../../interfaces/maintenance-status.interface';
import { Permissions } from '../../../interfaces/permissions.interface';
import { DetailsAlertComponent } from './details-alert/details-alert.component';
import { AlertData } from '../../../interfaces/alert.interface';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { BasicAlertComponent } from '../../resources/dialogs/basic-alert/basic-alert.component';

@Component({
    selector: 'app-maintenance-mode',
    templateUrl: './maintenance-mode.component.html',
    styleUrl: './maintenance-mode.component.css',
    standalone: false
})
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;

  btnSmall: boolean = false;
  txtBuscador:string;

  activateMaintenanceModeEnabled: boolean;
  maintenancesHistoryEnabled: boolean;

  constructor(
    private _systemAdminService: SystemAdminService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService, 
    private _router: Router,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.hasError = false;
    this.isLoading = true;
    this.maintenanceStatus = false;
    this.errorStr = "";
    this.maintenanceHistory = [];
    this.txtBuscador = '';
    this.activateMaintenanceModeEnabled = true;
    this.maintenancesHistoryEnabled = true;
    this.btnSmall = window.innerWidth <= 1608;
  }

  ngOnInit(): void {
    this.getMaintenanceStatus();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('ERR_NPE000: Ocurrió un error inesperado.');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M01ADSI');
            if(modPerm.length > 0){
              let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F05MOMA');
              if(funPerm.length > 0){
                let activateMaintenanceModeEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01AMMA');
                if(activateMaintenanceModeEnabled.length > 0){
                  this.activateMaintenanceModeEnabled = activateMaintenanceModeEnabled[0].access > 0;
                }
  
                let maintenancesHistoryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02HIMA');
                if(maintenancesHistoryEnabled.length > 0){
                  this.maintenancesHistoryEnabled = maintenancesHistoryEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('ERR_PAD001: Ocurrió un error inesperado.');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('ERR_PAD002: Ocurrió un error inesperado.');
        }else{
          this._resourcesService.openSnackBar(`ERR_PAD003: ${error.error.msg}`);
        }
      }
    });
  }

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

      let idUser = localStorage.getItem('idusuario')!;
      let maintenanceStatus: MaintenanceStatusResponse = await lastValueFrom(this._systemAdminService.getMaintenanceStatus(idUser, 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
    }
  }

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

      if(!this.hasError){
        let permissionsEnc = localStorage.getItem('permisos');
        let permissionsDec = await this._encService.decrypt(permissionsEnc!);
        let permissionsArr: Permissions = JSON.parse(permissionsDec);

        let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
        let funPerm = modPerm.children.filter(item => item.id == 'S002V01F05MOMA')[0];

        this.activateMaintenanceModeEnabled = funPerm.children.filter(item => item.id == 'S002V01P01AMMA')[0].access > 0;
        this.maintenancesHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P02HIMA')[0].access > 0;
        
        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;
    }
  }

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

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

  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,
        width: '520px',
        maxWidth: '520px',
      });

      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._resourcesService.openSnackBar(msg);
    }
  }

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