import { HttpErrorResponse, HttpHeaderResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { BulkimportService } from 'src/app/services/fnd/bulkimport.service';

@Component({
  selector: 'app-mappingruleedit',
  templateUrl: './mappingruleedit.component.html',
  styleUrls: ['./mappingruleedit.component.scss']
})
export class MappingruleeditComponent implements OnInit {
  public entryForm: FormGroup;
  selectedFile: File[]=[];
  id;
  datajson;
  transform:boolean = false;
  checkTransform:boolean = true;
  mapperdata;
  tdata: any = {};
  entityname;
  description;
  constructor(private _fb: FormBuilder, private router: Router,private toastr: ToastrService,
    private route: ActivatedRoute,private dataservice:BulkimportService) { }

  ngOnInit(): void {
    this.id = this.route.snapshot.params["id"];
    console.log("update with id = ", this.id);
    

    this.dataservice.getMappingDetailsById(this.id).subscribe(data => {
      this.tdata = data;
      this.serverData = JSON.parse(data.mapping_rule);
      console.log(this.tdata);
    },
    (err) => {
      console.log(err);
    });

  console.log(this.tdata);
  // this.entryForm.patchValue({
  //   entity_name: this.entityname,
  //   description: this.description,
  // });
  // console.log(this.entryForm.value);
  }

  getById(id: number) {

  }

  serverData = [];

  toastrShown: boolean = false;
  onSubmit(){
    this.tdata.mapping_rule = JSON.stringify(this.serverData);
    console.log(this.tdata);
    this.dataservice.updateMappingData(this.tdata, this.id).subscribe((data)=>{
      console.log(data);
      if (data.operationStatus) {
        this.toastr.warning(data.operationMessage);
      }else{
        if (!this.toastrShown) {
          this.toastrShown = true; // Set the flag to indicate that the toastr message has been shown
          this.toastr.success("Update Successfully");
          setTimeout(() => {
            this.router.navigate(["../../all"], { relativeTo: this.route });
          }, 500);
        }
      }
    }, (error: HttpHeaderResponse)=>{
      console.log(error);
      if(error.status===202){
        this.toastr.success("Update Succesfully");
      }
      if(error.status===404){
        this.toastr.error("Not Update");
      }
      if(error.status===400){
        this.toastr.error("Not Update");
      }
    });
    setTimeout(() => {
      this.router.navigate(["../../all"], { relativeTo: this.route });
    },500);
  }

  Updating(){
    console.log(this.tdata);
    this.dataservice.updateData(this.tdata, this.id).subscribe(data=>{
      console.log(data);
      // this.ngOnInit();
    }, (error: HttpHeaderResponse)=>{
      console.log(error);
    });
  }

  goback(){
    this.router.navigate(["../../all"], { relativeTo: this.route });
  }



  headerData;
  getColumns(table){
    console.log(table);
    // console.log(this.getbyiddata.entityName);
    this.dataservice.getColumnNames(table).subscribe((data) => {
      console.log(data);
      this.headerData = data;
  });
}


  
  getHeaderFieldData(){
    if(this.tdata.entity_name){
      this.dataservice.getColumnNames(this.tdata.entity_name).subscribe(data =>{
        console.log(data);
        const objectArray = data.map(fieldname => ({
          headerName: fieldname,
          value: "",
        }));
        // console.log(objectArray);
       const headerdata= JSON.stringify(objectArray);
       this.serverData = JSON.parse(headerdata);
      })
    }else{
      this.toastr.warning("Entity Name is Required")
  }
  }

  showdropdown = false;
  chooseFile(event){
    console.log(event);
    this.selectedFile = event.target.files[0];
    if(event){   this.showdropdown = true;}
 
  }

  valueofField;
  getDDFieldData(){
    if(this.tdata.fileType && this.selectedFile){
      this.dataservice.getDDforMappingRule(this.selectedFile,this.tdata.fileType).subscribe(data =>{
        console.log(data);
        this.valueofField = data.body;
      },(error)=>{
        if(error.status === 404){
          this.toastr.error("Sheet not found")
        }
        if(error.status >= 500 && error.status <= 599){
          this.toastr.error("Server Error")
        }
      })
    }else{
      this.toastr.warning("Sheet name and file is required")
  }
}

}
