import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnDestroy, OnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
} from '@angular/forms';
import {
  MatDialog,
  MatDialogRef,
  MAT_DIALOG_DATA,
} from '@angular/material/dialog';
import { tap } from 'rxjs/operators';
import { DocumentService } from 'src/app/services/document.service';
import { ToastService } from 'src/app/services/toast.service';
@Component({
  selector: 'app-modal-generate-document',
  templateUrl: './modal-generate-document.component.html',
  styleUrls: ['./modal-generate-document.component.scss'],
})
export class ModalGenerateDocumentComponent implements OnInit, OnDestroy {
  public templatesList = [
    {
      id: '',
      name: '',
    },
  ];
  public isLoading = false;
  public data!: [];
  public errorMsg = '';
  private payload: any;
  public isLoadingResult = false;
  public form: FormGroup;
  public submitted = false;
  private isFileName = false;
  private fileName!: string;
  constructor(
    public dialog: MatDialog,
    private reporting: DocumentService,
    private toast: ToastService,
    private formBuilder: FormBuilder,
    @Inject(MAT_DIALOG_DATA) public dataProject: any,
    @Inject(DOCUMENT) private document: Document,
    public dialogRef: MatDialogRef<ModalGenerateDocumentComponent>
  ) {
    this.document.body.classList.add('pop-report');
    this.form = this.formBuilder.group({
      template: ['', [Validators.required]],
    });
  }

  ngOnInit(): void {
    this.reporting
      .listTemplate( this.dataProject.objectName)
      .pipe(
        tap((res: any) => {
          res.success
            ? (this.templatesList = res.templates)
            : this.toast.showError(
                'Une erreur est survenue pour lister vos templates'
              );
        })
      )
      .subscribe();

    this.form.get('template')?.valueChanges.subscribe((data) => {
      this.payload = {
        templateId: data,
        templateName: this.getTemplateName(data),
        activeModuleId: this.dataProject.projetsid ? this.dataProject.projetsid : this.dataProject.potentialid,
        activeModuleName: this.dataProject.objectName,
      };
    });
  }

  public closeDialog() {
    this.dialogRef.close();
  }

  public generateReporting() {
    this.isLoading = true;
    this.reporting.genetateDocuments(this.payload, this.fileName).subscribe(
      (data: boolean) => {
        this.isLoading = false;
        if (data) {
          this.dialogRef.close();
        }
      },
      (err: any) => {
        this.toast.showError('Le fichier de template est introuvable.');
      }
    );
  }

  get f(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }

  public getFileName(payload?: any) {
    this.submitted = true;

    if (this.form.invalid || this.isLoading) {
      this.toast.showError('Merci de verifier le champ requis');
      return;
    }
    this.isLoading = true;
    this.isFileName = false;
    this.reporting.getNameDocuments(this.payload).subscribe((res: any) => {
      if (res.success) {
        this.fileName = res.fileName;
        this.isFileName = true;
        this.isLoading = false;
        this.generateReporting();
      } else {
        this.toast.showWaring('Le fichier de template est introuvable !');
        this.isLoading = false;
        this.isFileName = false;
      }
    });
  }

  private getTemplateName(id: string) {
    const response = this.templatesList.filter((res) => {
      return res.id === id;
    });

    return response[0].name;
  }
  public textButton() {
    if (this.isLoading) {
      return 'Génération en cours ...  ';
    }

    return 'Générer';
  }
  ngOnDestroy(): void {
    this.document.body.classList.remove('pop-report');
  }
}
