import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { EnviarInfoService } from '../../../Administrador/services/enviar-info.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MAT_DIALOG_DATA, MatDialog, MatDialogActions, MatDialogClose, MatDialogContent } from '@angular/material/dialog';
import { DomSanitizer } from '@angular/platform-browser';
import { CircularService } from '../../../Administrador/services/circular.service';
import { MatIcon } from '@angular/material/icon';
import { CommonModule } from '@angular/common';
import { RegistroAcademicoService } from '../../services/registroAcademico.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-circular-hijos',
  templateUrl: './circular-hijos.component.html',
  styleUrl: './circular-hijos.component.css'
})
export class CircularHijosComponent implements OnInit {
  public color: string = '';
  public textColor: string = '';
  isLoading: boolean = true;
  private id: string = '';
  dataAlum: any;
  public columnas: string[] = ['titulo', 'publicadaPor', 'importancia', 'fechaPublicacion', 'adjuntos', 'acciones'];
  public dataSource = new MatTableDataSource<any>();

  @ViewChild(MatPaginator, { static: true }) paginator!: MatPaginator;

  constructor(private _enviarInfo: EnviarInfoService, public dialog: MatDialog, private circularService: CircularService, private sanitizer: DomSanitizer,
    private _registro: RegistroAcademicoService, private route: ActivatedRoute
  ) {

  }

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      const id = params.get('id');

      this.id = atob(id || '');
    });
    this._enviarInfo.currentTextColor.subscribe(textColor => {
      this.textColor = textColor;
    });
    this._enviarInfo.currentColor.subscribe(color => {
      this.color = color;
    });
    this._registro.getOne(this.id).subscribe((data: any) => {
      this.dataAlum = data;
      if (this.dataAlum) {
        this.getCirculares();
      }
    });

  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  openDialog(circular: any) {
    this.dialog.open(ModalCircular, {
      data: { titulo: circular.titulo, contenido: this.sanitizer.bypassSecurityTrustHtml(circular.contenido) }
    });
  }

  buscarArchivo(id: string, nombre: string) {
    let separar = nombre.split('.');
    let extension = separar[separar.length - 1];
    let idF = `${id}.${extension}`;
    return this.circularService.getFile(idF).subscribe((response: any) => {
      window.open(response, '_blank');
    });
  }

  getCirculares() {
    console.log(this.dataAlum[0].idUsuario)
    return this.circularService.getByUser(this.dataAlum[0].idUsuario).subscribe((response: any) => {
      
      this.isLoading = false;
      this.dataSource = new MatTableDataSource<any>(response.filter((filtro: any) => filtro.estado === 'Activo'));
      this.dataSource.paginator = this.paginator;
      response.forEach((item: any) => {
        if (typeof item.jsonAdjuntos === 'string') {
          item.jsonAdjuntos = JSON.parse(item.jsonAdjuntos);
        }
        if (!Array.isArray(item.jsonAdjuntos)) {
          item.jsonAdjuntos = [];
        }
      });

      return response;
    });
  }
}

@Component({
  selector: 'app-circular1-hijos',
  templateUrl: './visualizarCircular.html',
  styleUrl: './circular-hijos.component.css',
  standalone: true,
  imports: [MatDialogContent, MatDialogActions, MatDialogClose, MatIcon, CommonModule,]
})

export class ModalCircular {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) {
  }
}
