import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DecimalPipe, DOCUMENT } from '@angular/common';
import { saveAs } from 'file-saver';
import { StorageService } from 'src/app/core/services/storage.service';
import { getAllDatas,getListViewElements} from 'src/app/custom/common'
import { DataService } from 'src/app/core/services/data.service';



@Component({
  selector: 'app-modal-data-export',
  templateUrl: './modal-data-export.component.html',
  styleUrls: ['./modal-data-export.component.scss']
})
export class ModalDataExportComponent implements OnInit {
  public form: FormGroup;
  public submitted = false;
  public currentList : any;
  public listViews : any;
  public csvHeader : any;
  public records : any;
  public fileName : any;
  public selected = 1 ;
  public checkList = [
    // { id: 1, value: 'Exporter les données de la liste courante', formControlName: "currentList"},
    { id: 1, value: 'Exporter toutes les données', formControlName: "allData"}
  ];
  public moduleName = '';
  public domaine = '';
  public isFirstGetData:boolean = true;


  constructor(
    public dialog: MatDialog,
    @Inject(MAT_DIALOG_DATA) public data: any,
    @Inject(DOCUMENT) private document: Document,
    public storage: StorageService,
        public dataService: DataService,
    private formBuilder: FormBuilder
  ) {
    this.form = this.formBuilder.group({
      currentList: true,
      allData: false
    });
  }

  ngOnInit(): void { 
    this.currentList = this.data.currentList;
    this.listViews = this.data.listViews[0].fields;
    this.records = this.data.records;
    this.fileName = this.data.fileName;
  }

  // async loadData(){
  //   const dd = this.storage.getItem('__domaineDD');
  //   const __domainedd = dd ? JSON.parse(dd) : {}
  //   this.moduleName = __domainedd?.modulename
  //   this.domaine = __domainedd?.domaine
  //   const lvs =  await getListViewElements(this.moduleName,this.dataService)
  //   this.listViews = lvs[this.moduleName].data.ListeView.list
  //   const datas = await getAllDatas(this.domaine, this.moduleName, this.dataService, this.isFirstGetData)
  //   this.records = datas[this.moduleName];
  //   console.log(this.listViews)
  // }
  
  public closeDialog() {
    this.dialog.closeAll();
  }

  exporter(selected : any) {
    this.submitted = true;
    if(selected === 1) {
      this.exportCurrentListView();
    }
    if(selected === 0) {
      this.exportAllData();
    }
    this.closeDialog();
  }

  public exportCurrentListView() {
    var fields = this.listViews.map((res : any) => {
      if( res.name === this.currentList ) {
        return res.fields;
      }
    })
    
    fields = fields.filter(function(x : any){
      return x !== undefined;
    })

    this.csvHeader = fields[0].map((res : any) => {
      return res.name;
    })

    let csvHeaderReplacement = fields[0].map((res : any) => {
      return res.displayName ? res.displayName : res.name;
    });
    
    // console.log("records : ", this.records);
    return this.downloadFile(this.csvHeader, this.records, csvHeaderReplacement); 
  }

  public exportAllData() {
    let csvHeader = Object.keys(this.records[0]).filter(function(x : any){
      return !x.includes('cf') && !x.includes('id') && (x !== "label");
    });
    return this.downloadFile(csvHeader, this.records, csvHeader);
  }

  public downloadFile(header: string[], data: any[], headerReplacement: string[]): void {
    try {
      // Fonction de replacer pour formater les valeurs
      const replacer = (key: any, value: any): string => {
        if (value === '' || value === null) return '';
        if (!isNaN(Number(value))) return value.toString().replace('.', ',');
        return value;
      };
  
      // Convertir les données en CSV
      const csv = data.map((row: any) =>
        header
          .map((fieldName: string) => {
            const fieldValue = row[fieldName]?.name || row[fieldName];
            return JSON.stringify(fieldValue, replacer);
          })
          .join(';')
      );
  
      // Ajouter l'en-tête de remplacement au début du CSV
      csv.unshift(headerReplacement.join(';'));
  
      // Convertir le tableau CSV en une chaîne de caractères
      const csvArray = csv.join('\r\n');
  
      // Créer un Blob avec le bon encodage UTF-8
      const blob = new Blob(['\uFEFF' + csvArray], {
        type: 'text/csv; charset=utf-8',
      });
  
      // Télécharger le fichier
      saveAs(blob, `${this.fileName}.csv`);
    } catch (error) {
      console.error('Erreur lors de la génération du fichier CSV:', error);
    }
  }

}
