import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Formaservice} from './Forma.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 { Formacardvariable } from './Forma_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Forma',
  templateUrl: './Forma.component.html',
  styleUrls: ['./Forma.component.scss']
})
export class FormaComponent implements OnInit {
  cardButton = Formacardvariable.cardButton;
  cardmodeldata = Formacardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Formacardvariable.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 = 'Forma_formCode'
tableName = 'Forma';  checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Formaservice,
    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({
names : [null],

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

phonetest: ['+91'],

paragraphtest : [null],

passwordss : [null],
confirmpasswordss : [null],

textareatest : [null],

datetest : [null],

datetimetest : [null],

emailtest : [null],

toggletest : [false],

urltest : [null],

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

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

recaptchass : ['', [Validators.required,this.checkrecaptchass.bind(this)]],

documentss : [null],

selectstat : [null],

radiotest : [null],

  
 
test1:[false],
   

 
test2:[false],
   










currencyss : [null, { updateOn: 'blur' }],


 







    }, {
        validator: ConfirmedpasswordssValidator('passwordss', 'confirmpasswordss')





































  }); // 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 === "Forma_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.generaterecaptchass()




















  }






































FileDataImageuploadtest: any[];
  selectedImageuploadtest: any[];

FileDataAudiotest: any[];
  selectedAudiotest: any[];

FileDataVideotest: any[];
  selectedVideotest: 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.selectedfileuploadtest = [];
    this.mainService.uploadfilegetByIdfileuploadtest(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatafileuploadtest = uploaddata;
    
    })

    this.selectedimageuploadtest = [];
    this.mainService.uploadImageuploadtestgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataimageuploadtest = uploaddata;
    
    })

    this.selectedaudiotest = [];
    this.mainService.uploadAudiotestgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataaudiotest = uploaddata;
    
    })

    this.selectedvideotest = [];
    this.mainService.uploadVideotestgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatavideotest = 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.selectedfileuploadtest.length; i++){

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

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

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

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

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

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

  this.mainService.uploadVideotest(data.id,this.tableName,this.selectedvideotest[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.selectedfileuploadtest.length; i++){

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

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

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

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

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

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

  this.mainService.uploadVideotest(data.id,this.tableName,this.selectedvideotest[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.FileDatafileuploadtest = [];
this.selectedfileuploadtest =[];

this.FileDataImageuploadtest = [];
this.selectedImageuploadtest =[];

this.FileDataAudiotest = [];
this.selectedAudiotest =[];

this.FileDataVideotest = [];
this.selectedVideotest =[];




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

} 




isValidPhonetest(phone: string): boolean {
  const phonePattern = /^(\+[1-9][0-9]{0,2})?[1-9][0-9]{9}$/;
  return phonePattern.test(phone);
}

rsModalparagraphtest = false;  
 goToReplaceStringparagraphtest (row){
						    this.rowSelected = row;     this.rsModalparagraphtest  =true;   }

newpHidepasswordss: boolean = true;
 newIconpasswordss: string = "eye"; 
newShapeChangerpasswordss() {
this.newpHidepasswordss = !this.newpHidepasswordss;  
 if(this.newpHidepasswordss){
this.newIconpasswordss = 'eye'   } else {     this.newIconpasswordss = 'eye-hide'   }
} 

 newaddpHidepasswordss: boolean = true;
 newaddIconpasswordss: string = "eye";
newaddChangerpasswordss() {   this.newaddpHidepasswordss = !this.newaddpHidepasswordss;
 if(this.newaddpHidepasswordss){     this.newaddIconpasswordss = 'eye'   } else {
  this.newaddIconpasswordss = 'eye-hide'   } }

rsModaltextareatest = false;   
goToReplaceStringtextareatest(row){
this.rowSelected = row;     this.rsModaltextareatest  =true;   }





isValidemailtest(email: string): boolean {
						 const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
						    return emailPattern.test(email);   }



isValidurltest(url: string): boolean {
						    return  /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(url);   } 
						goTourltestUrl(val){     window.open(val)   }





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

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

checkrecaptchass(control: AbstractControl): ValidationErrors | null {
  if (control.value !== this.recaptchassCode) {
    return { recaptchassMismatch: true };
  }
  return null;
}  

recaptchassMismatch = false;  

checkrecaptchassEdit(): void {
	  if (this.rowSelected.recaptchass  !== this. recaptchassCode) {
	  this. recaptchassMismatch = true;    } else {      this.recaptchassMismatch = false;    }  } 





updateradiotest (radiotest : string): void {    
 this.entryForm.get('radiotest').setValue(radiotest);   }

updateradiotestEdit(radiotest : string): void {    this.rowSelected.radiotest  =  radiotest }
						 ;



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

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

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

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

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

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

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

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

//currency  field start
   formatCurrencycurrencyss () {
    // Format the currency with two decimal places    
	this.rowSelected.currencyss = Number(this.rowSelected.currencyss ).toFixed(2);
    // Remove commas from the formatted currency   
	 this.rowSelected.currencyss = this.rowSelected.currencyss?.replace(/,/g, '');  }
  //currency  field end

// updateaction
}







export function ConfirmedpasswordssValidator(controlName: string, matchingControlName: string){
  return (formGroup: FormGroup) => {
      const control = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];
      if (matchingControl.errors && !matchingControl.errors.confirmedpasswordssValidator) {
          return;
      }
      if (control.value !== matchingControl.value) {
          matchingControl.setErrors({ confirmedpasswordssValidator: true });
      } else {
          matchingControl.setErrors(null);
      }
  }
}






































