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

idfemale : [null],

  
 
test1:[false],
   

 
test2:[false],
   


  
 
t1:[false],
   

 
t2:[false],
   

 
t4:[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 === "Adv1_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 

























  }
 ngOnDestroy(): void {
    if (this.editInterval) {
      clearInterval(this.editInterval);
    }
  }











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

FileDataImageupload_field2: any[];
  selectedImageupload_field2: any[];

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

FileDataAudio_field2: any[];
  selectedAudio_field2: any[];

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


FileDataVideo_field2: any[];
  selectedVideo_field2: any[];


 error; 
  getData() {
    this.mainService.getAll().subscribe((data) => {
      console.log(data);
      this.product = data;
this.product = [...this.product].reverse(); 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.selectedfileupload_field = [];
    this.mainService.uploadfilegetByIdfileupload_field(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatafileupload_field = uploaddata;
    
    })

    this.selectedfileupload_field2 = [];
    this.mainService.uploadfilegetByIdfileupload_field2(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatafileupload_field2 = uploaddata;
    
    })

    this.selectedimageupload_field = [];
    this.mainService.uploadImageupload_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataimageupload_field = uploaddata;
    
    })

    this.selectedimageupload_field2 = [];
    this.mainService.uploadImageupload_field2getById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataimageupload_field2 = uploaddata;
    
    })

    this.selectedaudio_field = [];
    this.mainService.uploadAudio_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataaudio_field = uploaddata;
    
    })

    this.selectedaudio_field2 = [];
    this.mainService.uploadAudio_field2getById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataaudio_field2 = uploaddata;
    
    })

    this.selectedvideo_field = [];
    this.mainService.uploadVideo_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatavideo_field = uploaddata;
    
    })

    this.selectedvideo_field2 = [];
    this.mainService.uploadVideo_field2getById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatavideo_field2 = 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.selectedfileupload_field.length; i++){

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  this.mainService.uploadVideo_field2(data.id,this.tableName,this.selectedvideo_field2[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.selectedfileupload_field.length; i++){

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  this.mainService.uploadVideo_field2(data.id,this.tableName,this.selectedvideo_field2[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.FileDatafileupload_field = [];
this.selectedfileupload_field =[];

this.FileDatafileupload_field2 = [];
this.selectedfileupload_field2 =[];

this.FileDataImageupload_field = [];
this.selectedImageupload_field =[];

this.FileDataImageupload_field2 = [];
this.selectedImageupload_field2 =[];

this.FileDataAudio_field = [];
this.selectedAudio_field =[];

this.FileDataAudio_field2 = [];
this.selectedAudio_field2 =[];

this.FileDataVideo_field = [];
this.selectedVideo_field =[];

this.FileDataVideo_field2 = [];
this.selectedVideo_field2 =[];


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

} 
updateismale (ismale : string): void {    
 this.entryForm.get('ismale').setValue(ismale);   }

updateismaleEdit(ismale : string): void {    this.rowSelected.ismale  =  ismale }
						 ;

updateidfemale (idfemale : string): void {    
 this.entryForm.get('idfemale').setValue(idfemale);   }

updateidfemaleEdit(idfemale : string): void {    this.rowSelected.idfemale  =  idfemale }
						 ;





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);
      })
      }
    }

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

      if(id){
      this.mainService.uploadfiledeletefileupload_field2(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);
      })
      }
    }

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

      if(id){
      this.mainService.uploadImageupload_field2delete(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);
      })
      }
    }

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

      if(id){
      this.mainService.uploadAudio_field2delete(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);
      })
      }
    }

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

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

// updateaction
}























