import { MatSnackBar } from '@angular/material/snack-bar';
import { AlertComponent } from './../../resources/dialogs/alert/alert.component';
import { SocketService } from './../../../services/socket.service';
import { AdviceAlertComponent } from './../../template/advice-alert/advice-alert.component';
import { MatDialog } from '@angular/material/dialog';
import { FunctionsService } from './../../../services/functions.service';
import { AdvicesService } from './../../../services/advices.service';
import { AdvicesResponse, SingleAdvice } from './../../../interfaces/advices.interface';
import { Router } from '@angular/router';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { EncService } from 'src/app/services/enc/enc.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Location } from '@angular/common';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { AdviceResponse } from 'src/app/interfaces/advice.interface';

@Component({
  selector: 'app-advices',
  templateUrl: './advices.component.html',
  styleUrls: ['./advices.component.css']
})
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;

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

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

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

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

  async getAdvices(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      
      let idUser = localStorage.getItem('idusuario')!;
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser));

      let advices: AdvicesResponse = await lastValueFrom(this._advicesService.getAdvices(shortEnc.response.encrypted, 1));
      
      this.isLoading = false;
      this.hasError = advices.error;
      this.errorStr = advices.msg;

      if(!this.hasError){
        this.dataSource = new MatTableDataSource(advices.response);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
        this.hasAdvices = advices.response.length > 0;
      }
    }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;
      }
    }
  }

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

  back(){
    this._location.back();
  }

  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.encriptar(`${idAviso}`);
      let shortAvi = await lastValueFrom(this._encService.shortEncrypt(idAviEnc));

      let idEnc = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc!));

      let advice: AdviceResponse = await lastValueFrom(this._advicesService.getAdvice(shortAvi.response.encrypted, shortEnc.response.encrypted, 1));
      this.isSearching = false;
      
      this._dialog.open(AdviceAlertComponent, {
        data: advice.response
      });
    }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;
      }
    }
  }

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

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

  openAlert(idAviso: number, titulo: string){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '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.encriptar(`${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.openSnackBar(msg);
    }
  }

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

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