import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { AdvicesResponse, SingleAdvice } from '../../../interfaces/advices.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Location } from '@angular/common';
import { EncService } from '../../../services/enc.service';
import { Router } from '@angular/router';
import { AdvicesService } from '../../../services/advices.service';
import { FunctionsService } from '../../../services/functions.service';
import { ResourcesService } from '../../../services/resources.service';
import { MatDialog } from '@angular/material/dialog';
import { SocketService } from '../../../services/socket.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { Permissions } from '../../../interfaces/permissions.interface';
import { AdviceResponse } from '../../../interfaces/advice.interface';
import { AdviceAlertComponent } from '../../template/advice-alert/advice-alert.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-advices',
    templateUrl: './advices.component.html',
    styleUrl: './advices.component.css',
    standalone: false
})
export class AdvicesComponent implements OnInit {
  isLoading: boolean;
  isSearching: boolean;
  hasError: boolean;
  hasAdvices: boolean;
  errorStr: string;

  dataSource?: MatTableDataSource<SingleAdvice>;
  displayedColumns = ['id', 'titulo', 'caducidad', 'estado', 'acciones'];

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

  btnSmall: boolean = false;
  txtBuscador:string;

  advicesHistoryEnabled: boolean;
  newAdviceEnabled: boolean;
  editAdviceEnabled: boolean;

  constructor(
    private _location: Location,
    private _encService: EncService,
    private _router: Router,
    private _advicesService: AdvicesService,
    private _functionsService: FunctionsService,
    private _resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService, 
  ) {
    this.isLoading = true;
    this.isSearching = false;
    this.hasError = false;
    this.hasAdvices = false;
    this.errorStr = "";
    this.txtBuscador = '';
    this.advicesHistoryEnabled = true;
    this.newAdviceEnabled = true;
    this.editAdviceEnabled = true;
  }

  ngOnInit(): void {
    this.getAdvices();
    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 == 'S002V01F03CRAV');
              if(funPerm.length > 0){
                let advicesHistoryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01HIAV');
                if(advicesHistoryEnabled.length > 0){
                  this.advicesHistoryEnabled = advicesHistoryEnabled[0].access > 0;
                }

                let newAdviceEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02CNAV');
                if(newAdviceEnabled.length > 0){
                  this.newAdviceEnabled = newAdviceEnabled[0].access > 0;
                }

                let editAdviceEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P03EDAV');
                if(editAdviceEnabled.length > 0){
                  this.editAdviceEnabled = editAdviceEnabled[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 getAdvices(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      
      let idUser = localStorage.getItem('idusuario')!;
      let advices: AdvicesResponse = await lastValueFrom(this._advicesService.getAdvices(idUser, 1));
      
      this.hasError = advices.error;
      this.errorStr = advices.msg;

      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 == 'S002V01F03CRAV')[0];

        this.advicesHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P01HIAV')[0].access > 0;
        this.newAdviceEnabled = funPerm.children.filter(item => item.id == 'S002V01P02CNAV')[0].access > 0;
        this.editAdviceEnabled = funPerm.children.filter(item => item.id == 'S002V01P03EDAV')[0].access > 0;

        let advicesArr: SingleAdvice[] = [];
        for(const advice of advices.response){
          advice.IDAVISO = await this._encService.decrypt(advice.IDAVISO);
          advicesArr.push(advice);
        }
        
        this.dataSource = new MatTableDataSource(advicesArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
        this.hasAdvices = advices.response.length > 0;
      }
      
      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined || error.error == null){
        this.errorStr = "Ocurrió un error inesperado.";
      }else if(error.error.msg == undefined || error.error.msg == null){
        this.errorStr = "Ocurrió un error inesperado.";
      }else{
        this.errorStr = error.error.msg;
      }
    }
  }

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

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

  createAdvice(){
    this._router.navigate(['sam/ADSI/CRAV/nuevo']);
  }

  buildDate(date: string): string{
    let formattedDate = this._functionsService.orderDate(date)!;
    
    return formattedDate;
  }

  async showAlert(idAviso: number){
    try{
      this.isSearching = true;
      let idAviEnc = await this._encService.encrypt(`${idAviso}`);
      let idEnc = localStorage.getItem('idusuario')!;

      let advice: AdviceResponse = await lastValueFrom(this._advicesService.getAdvice(idAviEnc, idEnc, 1));
      this.isSearching = false;
      
      this._dialog.open(AdviceAlertComponent, {
        data: advice.response
      });
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.isSearching = false;
    }
  }

  async sendAdvice(idAviso: number){
    let idEnc = await this._encService.encrypt(`${idAviso}`);
    this._socketService.publishAdvice(idEnc);
  }

  async openEditor(idAviso: number){
    let idAviEnc = await this._encService.encrypt(`${idAviso}`);
    
    this._router.navigate(['sam/ADSI/CRAV/editar'], {
      queryParams: {
        idAvi: idAviEnc
      }
    });
  }

  openAlert(idAviso: number, titulo: string){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '300px',
      maxWidth: '300px',
      data: {
        icon: "warning",
        title: '¡Cuidado!',
        description: `¿Está seguro de querer eliminar el aviso "${titulo}"?`
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this.deleteAdvice(idAviso);
      }
    });
  }

  async deleteAdvice(idAviso: number){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idAdvice = await this._encService.encrypt(`${idAviso}`);
      
      await lastValueFrom(this._advicesService.deleteAdvice({
        id_user: idUser,
        id_advice: idAdvice,
        linea: 1
      }));
      
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
  
      this.getAdvices();
    }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);
    }
  }
}
