import { Component, OnInit } from '@angular/core';


import { ToastrService } from 'ngx-toastr';
import { ActivatedRoute, Router } from '@angular/router';
import { College } from 'src/app/models/fnd/play';
import { student } from 'src/app/models/fnd/Studentadd';
import { AbstractControl, FormBuilder, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { ValidationError } from 'src/app/models/fnd/ValidationError';
import { demotestservice } from './demotest.service';
declare var JsBarcode: any;
  @Component({
  selector: 'app-editstepper',
  templateUrl: './demotest.component.html',
  styleUrls: ['./demotest.component.scss']
})
export class demotestComponent implements OnInit {
  updated = false;
  stringJson: any;
  customerId: string = '';
  selectedFile!: File;
  fileName = '';

  id: number;
  errorFields: ValidationError[] = [];
  appToUpdate: College = null;
  trained = false;

  json: string = "";
  luisApp =
    {
      name: '',
      created: 1,
      trained: 1,
      tested: 1,
      updated: 1,
      published: 1,

    };
  // Layout direction changing
  layout = {
    direction: "vertical",
    block1: "clr-col-lg-3 clr-col-12 ",
    block2: "clr-col-lg-9 clr-col-12 ",
  };

  timelineStyle = { 
 step0: { state: "current", open: true, failed: false }, 
    step1: { state: "not-started", open: false, failed: false },
    step2: { state: "not-started", open: false, failed: false },
};
public FormaentryForm: FormGroup;
public Advtest1entryForm: FormGroup;
  submitted = false;
  rowSelected: any = {};
  modalcomplete = false;

  constructor( 
private mainService: demotestservice,

private demoregi_fb: FormBuilder, 
private advtest_fb: FormBuilder, 
private router: Router,
 private route: ActivatedRoute,
    private toastr: ToastrService,
  ) { }

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


 this.FormaentryForm = this.demoregi_fb.group({ 
name : [null],

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

phone_number: ['+91'],

paragraph_field : [null],

password_field : [null],
confirmpassword_field : [null],

textarea : [null],

date_field : [null],

datetime_field : [null],

email_field : [null],

toggle_switch : [true],

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

url_field : [null],

recaptcha : ['', [Validators.required,this.checkrecaptcha.bind(this)]],

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


  });























this.generaterecaptcha()




 this.Advtest1entryForm = this.advtest_fb.group({ 
name : [null],

country : [null],

gender : [null],

  
 
villae:[false],
   

 
home:[false],
   










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

qrcode_field : [null],

barcode_field : [null],


  });






















 const stepId = this.id; // or from route/query/etc
 
    this.getResolvedDataFromStepper(stepId).subscribe(res => {
      console.log('response get ', res);

      if (res === null) {
        this.showEmptyForm();
      } else {
 if (res['Forma']) {
 
 this.prefilldemoregiForm(res['Forma']);
        }

 if (res['Advtest1']) {
 
 this.prefilladvtestForm(res['Advtest1']);
        }
}
    });

  }
showEmptyForm(): void {
    console.log('No config found. Showing empty form.');
    // You can choose to show one or both based on some logic

 this.FormaentryForm.reset();

 this.Advtest1entryForm.reset();
  }  prefilldemoregiForm(data: any): void {

    console.log(' demoregi data ', data)
    this.FormaentryForm.patchValue({
      id: data.id || '',
name: data.name || '',

number_field: data.number_field || '',

phone_number: data.phone_number || '',

paragraph_field: data.paragraph_field || '',

password_field: data.password_field || '',

textarea: data.textarea || '',

date_field: data.date_field || '',

datetime_field: data.datetime_field || '',

email_field: data.email_field || '',

toggle_switch: data.toggle_switch || '',

decimal_field: data.decimal_field || '',

url_field: data.url_field || '',

recaptcha: data.recaptcha || '',

percentage_field: data.percentage_field || '',

    });
  }  prefilladvtestForm(data: any): void {

    console.log(' advtest data ', data)
    this.Advtest1entryForm.patchValue({
      id: data.id || '',
name: data.name || '',

country: data.country || '',

gender: data.gender || '',

address: data.address || '',

fileupload_field: data.fileupload_field || '',

imageupload_field: data.imageupload_field || '',

audio_field: data.audio_field || '',

video_field: data.video_field || '',

currency: data.currency || '',

qrcode_field: data.qrcode_field || '',

barcode_field: data.barcode_field || '',

    });
  }
 getResolvedDataFromStepper(id: number): Observable<any> {
    console.log('get step config');

    return new Observable(observer => {
      this.mainService.gettabledata(id).subscribe(configList => {
        if (!configList || configList.length === 0) {
          console.log('empty config');
          observer.next(null);
          observer.complete();
          return;
        }

        const results: { [key: string]: any } = {};
        let processed = 0;

        configList.forEach(config => {
          const { table_name, table_id } = config;

          this.getByTableNameAndId(table_name, table_id).subscribe(data => {

            console.log('data is ', data);
            results[table_name] = data;

            processed++;
            if (processed === configList.length) {
              observer.next(results);  // emit combined data
              observer.complete();
            }

          }, error => {
            console.error(`Error loading data for table ${table_name}`, error);
            processed++;
            if (processed === configList.length) {
              observer.next(results);  // continue with what we have
              observer.complete();
            }
          });
        });

      }, error => {
        console.error("Error loading stepper config", error);
        observer.error(error);
      });
    });
  }



  getByTableNameAndId(tableName: string, id: number): Observable<any> {

    switch (tableName) {
   case 'Forma':
        return this.mainService.getFormaById(id); case 'Advtest1':
        return this.mainService.getAdvtest1ById(id);// aur bhi cases agar naye table add ho to
      default:
        throw new Error(`Unknown table name: ${tableName}`);
    }
  }
  // Change to Horizontal Layout
  changeToHorizonTal() {
    this.layout = {
      direction: "horizontal",
      block1: "clr-col-lg-12 clr-col-12 height container",
      block2: "clr-col-lg-12 clr-col-12 container",
    }
  }
  // Change to Vertical Layout
  changeToVertical() {
    this.layout = {
      direction: "vertical",
      block1: "clr-col-lg-3 clr-col-12 ",
      block2: "clr-col-lg-9 clr-col-12 ",
    }
  }



  ondemoregiSave() {
    console.log('Form Submitted:', this.FormaentryForm.value);
    this.submitted = true;
    if (this.FormaentryForm.invalid) {

      console.log('invalid form ..');
      // Log all form errors
      Object.keys(this.FormaentryForm.controls).forEach(field => {
        const control = this.FormaentryForm.get(field);
        if (control && control.invalid) {
          console.log(`Error in field: ${field}`, control.errors);
        }
      }
      );
      return;
    }
    this.ondemoregiCreate();
  }

  ondemoregiCreate() {




























    this.mainService.createForma(this.FormaentryForm.value).subscribe(
      (data) => {
        console.log('adding data ', data);
        this.customerId = data.id;

        console.log('id is  ', this.customerId);


 const tableId = data.id;
        const tableName = 'Forma';
        const stepperId = this.id;

        // Save stepper config
        this.mainService.saveStepperConfig(stepperId, tableId, tableName).subscribe(() => {
          this.toastr.success("Stepper Config Saved");
        });        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);





























      }, (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");
        }
      });
    this.rowSelected = this.FormaentryForm.value;

    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }


  onadvtestSave() {
    console.log('Form Submitted:', this.Advtest1entryForm.value);
    this.submitted = true;
    if (this.Advtest1entryForm.invalid) {

      console.log('invalid form ..');
      // Log all form errors
      Object.keys(this.Advtest1entryForm.controls).forEach(field => {
        const control = this.Advtest1entryForm.get(field);
        if (control && control.invalid) {
          console.log(`Error in field: ${field}`, control.errors);
        }
      }
      );
      return;
    }
    this.onadvtestCreate();
  }

  onadvtestCreate() {






















    this.mainService.createAdvtest1(this.Advtest1entryForm.value).subscribe(
      (data) => {
        console.log('adding data ', data);
        this.customerId = data.id;

        console.log('id is  ', this.customerId);


 const tableId = data.id;
        const tableName = 'Advtest1';
        const stepperId = this.id;

        // Save stepper config
        this.mainService.saveStepperConfig(stepperId, tableId, tableName).subscribe(() => {
          this.toastr.success("Stepper Config Saved");
        });        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);








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

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

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

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

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

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

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

  this.mainService.uploadVideo_field(data.id,tableName,this.selectedvideo_field[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");
        }
      });
    this.rowSelected = this.Advtest1entryForm.value;

    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }


  onnext() {
    this.router.navigate(["../../main/workflow"], { relativeTo: this.route });
  }
  reset() {
    this.json = "";
    this.luisApp =
    {
      name: '',
      trained: 1,
      tested: 1,
      updated: 1,
      published: 1,
      created: 1,

    };

    this.timelineStyle = {
      step0: { state: "current", open: true, failed: false },
      step1: { state: "not-started", open: false, failed: false },
      step2: { state: "not-started", open: false, failed: false },
 };
  }
  current() {
    console.log(this.timelineStyle)
    this.stringJson = JSON.stringify(this.timelineStyle);
    console.log("String json object :", this.stringJson);

  }




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

rsModalparagraph_field = false;  
 goToReplaceStringparagraph_field (row){
						    this.rowSelected = row;     this.rsModalparagraph_field  =true;   }

newpHidepassword_field: boolean = true;
 newIconpassword_field: string = "eye"; 
newShapeChangerpassword_field() {
this.newpHidepassword_field = !this.newpHidepassword_field;  
 if(this.newpHidepassword_field){
this.newIconpassword_field = 'eye'   } else {     this.newIconpassword_field = 'eye-hide'   }
} 

 newaddpHidepassword_field: boolean = true;
 newaddIconpassword_field: string = "eye";
newaddChangerpassword_field() {   this.newaddpHidepassword_field = !this.newaddpHidepassword_field;
 if(this.newaddpHidepassword_field){     this.newaddIconpassword_field = 'eye'   } else {
  this.newaddIconpassword_field = 'eye-hide'   } }

rsModaltextarea = false;   
goToReplaceStringtextarea(row){
this.rowSelected = row;     this.rsModaltextarea  =true;   }





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





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

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

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

checkrecaptcha(control: AbstractControl): ValidationErrors | null {
  if (control.value !== this.recaptchaCode) {
    return { recaptchaMismatch: true };
  }
  return null;
}  

recaptchaMismatch = false;  

checkrecaptchaEdit(): void {
	  if (this.rowSelected.recaptcha  !== this. recaptchaCode) {
	  this. recaptchaMismatch = true;   
 } else {  
    this.recaptchaMismatch = false;    }  } 







updategender (gender : string): void {    
 this.Advtest1entryForm.get('gender').setValue(gender);   }

updategenderEdit(gender : string): void {    this.rowSelected.gender  =  gender }
						 ;



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

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

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

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

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

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

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

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

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



//bar code field start 
     generateBarcodebarcode_field(value) {
      const barcodeValue = value;
      const barcodeElement = document.getElementById("barcodebarcode_field"); 
      if (barcodeElement) {         if (barcodeValue) {
          JsBarcode(barcodeElement, barcodeValue, {             format: "CODE128"
          });         } else {
          // Clear the barcode if the input is empty
          barcodeElement.innerHTML = '';         }       }     }
         //    bar code field end 







































FileDataImageupload_field: any[];
  selectedImageupload_field: any[];

FileDataAudio_field: any[];
  selectedAudio_field: any[];

FileDataVideo_field: any[];
  selectedVideo_field: any[];








// updateaction
}







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










































