import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Formbservice} from './Formb.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 { Formbcardvariable } from './Formb_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Formb',
  templateUrl: './Formb.component.html',
  styleUrls: ['./Formb.component.scss']
})
export class FormbComponent implements OnInit {
  cardButton = Formbcardvariable.cardButton;
  cardmodeldata = Formbcardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Formbcardvariable.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 = 'Formb_formCode'
tableName = 'Formb';  checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Formbservice,
    private alertService: AlertService,
    private toastr: ToastrService,
    private _fb: FormBuilder,
  ) { }
// 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({
decimald : [null,[Validators.required]],

percentagef : [null,[Validators.required]],

recaptchaf : [null, [Validators.required,this.checkrecaptchaf.bind(this)]],

documentseq : [null],



selectst : [null],

radiod : [null],

  
 
a:[false],
   

 
b:[false],
   











 























  }); // 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 === "Formb_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 




this.generaterecaptchaf()




















  }


















FileDataImageuploadh: any[];
  selectedImageuploadh: any[];

FileDataAudioh: any[];
  selectedAudioh: any[];

FileDataVideoh: any[];
  selectedVideoh: 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.selectedfileuploadj = [];
    this.mainService.uploadfilegetByIdfileuploadj(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatafileuploadj = uploaddata;
    
    })

    this.selectedimageuploadh = [];
    this.mainService.uploadImageuploadhgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataimageuploadh = uploaddata;
    
    })

    this.selectedaudioh = [];
    this.mainService.uploadAudiohgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataaudioh = uploaddata;
    
    })

    this.selectedvideoh = [];
    this.mainService.uploadVideohgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatavideoh = 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");
        }

















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

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

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

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

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

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

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

  this.mainService.uploadVideoh(data.id,this.tableName,this.selectedvideoh[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");
        }
















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

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

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

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

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

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

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

  this.mainService.uploadVideoh(data.id,this.tableName,this.selectedvideoh[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.FileDatafileuploadj = [];
this.selectedfileuploadj =[];

this.FileDataImageuploadh = [];
this.selectedImageuploadh =[];

this.FileDataAudioh = [];
this.selectedAudioh =[];

this.FileDataVideoh = [];
this.selectedVideoh =[];


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

} 




recaptchafCode = '';  
generaterecaptchaf (): void {
  const possibleCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const codeLength = 6; // Change to desired length

  let recaptchaf= '';
  for (let i = 0; i < codeLength; i++) {
    const randomIndex = Math.floor(Math.random() * possibleCharacters.length);
    recaptchaf += possibleCharacters.charAt(randomIndex);
  }
  this.recaptchafCode = recaptchaf;
}

checkrecaptchaf(control: AbstractControl): ValidationErrors | null {
  if (control.value !== this.recaptchafCode) {
    return { recaptchafMismatch: true };
  }
  return null;
}  

recaptchafMismatch = false;  

checkrecaptchafEdit(): void {
	  if (this.rowSelected.recaptchaf  !== this. recaptchafCode) {
	  this. recaptchafMismatch = true;    } else {      this.recaptchafMismatch = false;    }  } 







updateradiod (radiod : string): void {    
 this.entryForm.get('radiod').setValue(radiod);   }

updateradiodEdit(radiod : string): void {    this.rowSelected.radiod  =  radiod }
						 ;



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

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

filePreviewimageuploadh: string | ArrayBuffer | null = null;
FileDataimageuploadh: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedimageuploadh: File[]=[]; 
public onFileChangedimageuploadh(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDataimageuploadh[index].uploadedfile_name = files[i].name;
    this.selectedimageuploadh.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.FileDataimageuploadh[index] = {
          ...this.FileDataimageuploadh[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesimageuploadh(){
      this.FileDataimageuploadh.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowimageuploadh(index,id) {
      this.FileDataimageuploadh.splice(index, 1);

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

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

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

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

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

// updateaction
}























