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
  public insertFormButton_Field: FormGroup;

 
  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({
namek : [null],

gender : [null],

  
 
u:[false],
   

 
v:[false],
   

 
w:[false],
   












 
 
b:[null],
 

 
v:[null],
 


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



qrcode_field : [null],

barcode_field : [null],

 

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

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




 

































  }); // component_button200
// inser code start
  this.insertFormButton_Field = this._fb.group({
    active: 'toggle_switch',
    description: 'textarea',
    name: 'text',
  });

  // insert code end

 // 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 
































  // Subscribe to value changes for auto calculation
    this.entryForm.valueChanges.subscribe(() => {
      this.onInputChangecalculated_field('add');
    });

// Start polling for edit changes
    this.editInterval = setInterval(() => {
      if (this.modalEdit) {
        this.onInputChangecalculated_field('edit');
      }
    }, 200);


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







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

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

FileDataVideo_field: any[];
  selectedVideo_field: 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.selectedimageupload_field = [];
    this.mainService.uploadImageupload_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataimageupload_field = uploaddata;
    
    })

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

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











  //    bar code field start 
   setTimeout(function(){ 
		JsBarcode("#barcodebarcode_field", row?.barcode_field);
	     }, 500);
	   //    bar code field start










    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;
































//calculated field start
	
this.onInputChangecalculated_field ('edit');
 //calculated field end

    //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.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.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.selectedvideo_field.length; i++){

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

  this.mainService.uploadVideo_field(data.id,this.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");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  goToAdd(row) {
this.modalAdd = true; this.submitted = false;





this.FileDatafileupload_field = [];
this.selectedfileupload_field =[];

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

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

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













 this.getdatagrid_fieldData();








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

} 


updategender (gender : string): void {    
 this.entryForm.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

//Value List field start    
value_list_fieldMode;
searchcusttextvalue_list_field :any;    
 valueListModalvalue_list_field :boolean=false;
    openvalueListvalue_list_field(mode){
 this.valueListModalvalue_list_field=!this.valueListModalvalue_list_field ; 
      this.value_list_fieldMode = mode;     }
     customerdatavalue_list_field ;     
value_list_fielderror;
clickedvalue_list_fieldID:number;

getcustvalue_list_fieldID(id:number){    
 this.clickedvalue_list_fieldID=id;
						    console.log("clicked by id"+ id);
						    this.mainService.getById(id).subscribe((data) => {       console.log(data);
						         if(this.value_list_fieldMode == "ADD"){ 

							
 
							this.entryForm.get('namek').setValue(data.namek);
							 


						}else if(this.value_list_fieldMode == "EDIT"){

							
 
							this.rowSelected.namek= data. namek
							 


						}       });       this.valueListModalvalue_list_field =false;
						    }    //value List 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 

//datagrid datagrid_field  filed start    
productdatagrid_field;     
 rowsdatagrid_field :any[];
         getHeadersdatagrid_field () {          
			 this.rowsdatagrid_field = this.productdatagrid_field;         
  let headers: string[] = [];
          if(this.rowsdatagrid_field ) {             
this.rowsdatagrid_field.forEach((value) => {         
      Object.keys(value).forEach((key) => {
                if(!headers.find((header) => header == key)){
                  headers.push(key)             
    }         
              })                 
     })         
}
         
 return headers;      
   } 
 //datagrid datagrid_field filed end 
					    
getdatagrid_fieldData() {
    this.mainService.getdatagrid_fieldAll().subscribe((data) => {
      console.log(data);      this.productdatagrid_field  = data; 
    });
}






  // calculated field code start 


 
 calculated_fieldnumber_c; 
  

 
 calculated_fieldnumber_field; 
  


  calculated_fieldtotal;
  calculated_fieldcalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Addition"
  onInputChangecalculated_field(mode: 'add' | 'edit') {

  
    const lastObj = 0
    const lastObjstring = ''
    if (mode === 'add') {
      
 
      this.calculated_fieldnumber_c = this.entryForm.value.number_c || '';
       

 
      this.calculated_fieldnumber_field = this.entryForm.value.number_field || '';
       


    } else {

 
      this.calculated_fieldnumber_c = this.rowSelected.number_c;
 

 
      this.calculated_fieldnumber_field = this.rowSelected.number_field;
 

    }
    
 
    const number_cValue = parseFloat(this.calculated_fieldnumber_c) || 0;
     

 
    const number_fieldValue = parseFloat(this.calculated_fieldnumber_field) || 0;
     

    switch (this.calculated_fieldcalculateOperators) {
      case 'Addition':
        this.calculated_fieldtotal = (
          
 
          number_cValue +
           

 
          number_fieldValue +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.calculated_fieldtotal = (
          
 
          number_cValue -
           

 
          number_fieldValue -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.calculated_fieldtotal = (
          
 
          number_cValue *
           

 
          number_fieldValue *
           

         1).toString();

        break;
      case 'Division':

        this.calculated_fieldtotal = (
          
 
          number_cValue /
           

 
          number_fieldValue /
           

          1).toString();

        break;
      case 'Concatination':
        this.calculated_fieldtotal = `
          
 
          ${this.calculated_fieldnumber_c || ''}
           

 
          ${this.calculated_fieldnumber_field || ''}
           

          ${lastObjstring || ''}`;

        break;
      default:
        this.calculated_fieldtotal = '';
    }
  }


// updateaction

// insert button


modalInsertButton_Field = false; 
goToInsertButton_Field() {
  this.modalInsertButton_Field=true;
  }
onSubmitInsertButton_Field() {
  console.log(this.insertFormButton_Field.value);
  this.submitted=true;
  if (this.insertFormButton_Field.invalid) {
    return;
  }
  this.onInsertButton_Field();
}
onInsertButton_Field() {
    this.modalInsertButton_Field=false;
   this.mainService.insertButton_FieldLista(this.insertFormButton_Field.value).subscribe(data => {
     console.log('After add',data)
     if (data.status >=200 && data.status <=209) {
      this.toastr.success('Added successfully');
  }
if (data && data.id != null) {
        this.toastr.success('Added successfully');
      }  this.ngOnInit();
   },(error) => {
     console.error(error);
     if ( error.status >= 200 && error.status <= 299) {
       this.toastr.success("Update Successfully");
     } 
     if ( error.status >= 400 && error.status <= 499) {
       this.toastr.error("Update Failed");
     } 
     if ( error.status >= 500 && error.status <= 599) {
       this.toastr.error("Server Error");
     } 
     this.ngOnInit();
   });
     this.insertFormButton_Field.reset();
 }
//  insert buuton code end


}






























