import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Templateservice} from './Template.service';
import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators, ValidationErrors } from '@angular/forms';
import { ExtensionService } from 'src/app/services/fnd/extension.service';
import { DashboardContentModel2 } from 'src/app/models/builder/dashboard'; 
import { Templatecardvariable } from './Template_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
import { ActivatedRoute, Router } from '@angular/router';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Template',
  templateUrl: './Template.component.html',
  styleUrls: ['./Template.component.scss']
})
export class TemplateComponent implements OnInit {
  cardButton = Templatecardvariable.cardButton;
  cardmodeldata = Templatecardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Templatecardvariable.cardButton;
  cardmodal;  changeView(){
  this.isCardview = !this.isCardview;
  }
    beforeText(fieldtext: string): string { // Extract the text before the first '<'
    const index = fieldtext.indexOf('<');
    return index !== -1 ? fieldtext.substring(0, index) : fieldtext;
  }
  afterText(fieldtext: string): string { // Extract the text after the last '>'
    const index = fieldtext.lastIndexOf('>');
    return index !== -1 ? fieldtext.substring(index + 1) : '';
  }
  transform(fieldtext: string): string {
    const match = fieldtext.match(/<([^>]*)>/);
    return match ? match[1] : ''; // Extract the text between '<' and '>'
  }
 userrole;
  rowSelected :any= {};
  modaldelete=false;
  modalEdit=false;
  modalAdd= false;
  public entryForm: FormGroup;
  loading = false;
  product;
  modalOpenedforNewLine = false;
  newLine:any;
 additionalFieldsFromBackend: any[] = [];
  formcode = 'Template_formCode'
tableName = 'Template';  checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Templateservice,
    private alertService: AlertService,
    private toastr: ToastrService,
    private _fb: FormBuilder,
 private router: Router,  
    private route: ActivatedRoute  ) { }
// component button 
  ngOnInit(): void {
    if(this.cardmodeldata !== ''){
     this.cardmodal = JSON.parse(this.cardmodeldata);
    this.dashboardArray = this.cardmodal.dashboard.slice();
    console.log(this.dashboardArray)
    }
    this.userrole=this.userInfoService.getRoles();
    this.getData();
    this.entryForm = this._fb.group({
template : [null],




 



  }); // component_button200
 // form code start
    this.extensionService.getJsonObjectsByFormCodeList(this.formcode).subscribe(data => {
      console.log(data);
      const jsonArray = data.map((str) => JSON.parse(str));
      this.additionalFieldsFromBackend = jsonArray;
      this.checkFormCode = this.additionalFieldsFromBackend.some(field => field.formCode === "Template_formCode");
      console.log(this.checkFormCode);
      console.log(this.additionalFieldsFromBackend);
      if (this.additionalFieldsFromBackend && this.additionalFieldsFromBackend.length > 0) {
        this.additionalFieldsFromBackend.forEach(field => {
          if (field.formCode === this.formcode) {
            if (!this.entryForm.contains(field.extValue)) {
              // Add the control only if it doesn't exist in the form
              this.entryForm.addControl(field.extValue, this._fb.control(field.fieldValue));
            }
          }
        });
      }
    });
    console.log(this.entryForm.value);
    // form code end 





  }


FileDataUpload_template: any[];
  selectedUpload_template: any[];

 error; 
  getData() {
    this.mainService.getAll().subscribe((data) => {
      console.log(data);
      this.product = data;
 if(this.product.length==0){
        this.error="No Data Available"
     }   
    },(error) => {
      console.log(error);
      if(error){
       this.error="Server Error";
     }
    });
  }
  onEdit(row) {
    this.rowSelected = row;


    this.selectedupload_template = [];
    this.mainService.uploadUpload_templategetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataupload_template = uploaddata;
    
    })


    this.modalEdit = true;
  }
   onDelete(row) {
    this.rowSelected = row;
     this.modaldelete=true;
  }
  delete(id)
  {
    this.modaldelete = false;
    console.log("in delete  "+id);
    this.mainService.delete(id).subscribe(
      (data) => {
        console.log(data);
        this.ngOnInit();
  if (data) {				      this.toastr.success('Deleted successfully');      }
    });
  }
    onUpdate(id) {
    this.modalEdit = false;




    //console.log("in update");
    console.log("id  " + id);
    console.log(this.rowSelected);
    //console.log("out update");
    this.mainService.update(id, this.rowSelected).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Update Successfully");
        }
setTimeout(() => {
      this.ngOnInit();
    }, 500);


for (let i = 0; i < this.selectedupload_template.length; i++){

  this.mainService.uploadUpload_template(data.id,this.tableName,this.selectedupload_template[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("update Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Updated");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Updated");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  } 
onCreate() {
     this.modalAdd=false;




  this.mainService.create(this.entryForm.value).subscribe(
    (data) => {
      console.log(data);
  if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
setTimeout(() => {
      this.ngOnInit();
    }, 500);

for (let i = 0; i < this.selectedupload_template.length; i++){

  this.mainService.uploadUpload_template(data.id,this.tableName,this.selectedupload_template[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}


      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("Added Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Added");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Added");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  goToAdd(row) {
this.modalAdd = true; this.submitted = false;

this.FileDataUpload_template = [];
this.selectedUpload_template =[];


  }
 submitted = false;
onSubmit() {
  console.log(this.entryForm.value);
 this.submitted = true;
  if (this.entryForm.invalid) {
    return;
  }this.onCreate();

} 


filePreviewupload_template: string | ArrayBuffer | null = null;
FileDataupload_template: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedupload_template: File[]=[]; 
public onFileChangedupload_template(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDataupload_template[index].uploadedfile_name = files[i].name;
    this.selectedupload_template.push(files[i]);
    if (file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // Set the file preview source
        const filePreview = e.target?.result as string;
        this.FileDataupload_template[index] = {
          ...this.FileDataupload_template[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesupload_template(){
      this.FileDataupload_template.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowupload_template(index,id) {
      this.FileDataupload_template.splice(index, 1);

      if(id){
      this.mainService.uploadUpload_templatedelete(id).subscribe(data =>{
        console.log(data);
      })
      }
    }

  goToDataM(){
    this.router.navigate(['/cns-portal/datamanagement'],{ relativeTo: this.route });
  }

  
downloadCSV(tableName): void {
  this.mainService.downloadCSV(tableName).subscribe(response => {
    const blob = new Blob([response], { type: 'application/octet-stream' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${tableName}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  });
}// updateaction
}



