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

support: this._fb.array([this.initsupportForm()]),

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

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









childform: this._fb.array([this.initchildformForm()]),


 

















  }); // 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 === "Adv5_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.onInputChangeaddition('add');
    });

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

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

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








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

// one to many start
 initsupportForm() {    return this._fb.group({ 


 	
 description: [null],
 

 	
 name: [null],
 


});  }  
get supportcontrols() {return (this.entryForm.get("support") as FormArray).controls;  }
onAddsupport() {
(<FormArray>this.entryForm.get("support")).push(this.initsupportForm());  }
onRemovesupport(index: number) {
(<FormArray>this.entryForm.get("support")).removeAt(index);  }
 oneditsupport() {    this.supportcomponents.push({ 

 
description: "",
 

 
name: "",
 


	  });  }  
 deletesupportRow(index) {
 this.supportcomponents.splice(index, 1); 
 }  
supportcomponents;
 // one to many end 













// one to many start
 initchildformForm() {    return this._fb.group({ 


 	
 active: [null],
 

 	
 description: [null],
 

 	
 name: [null],
 


});  }  
get childformcontrols() {return (this.entryForm.get("childform") as FormArray).controls;  }
onAddchildform() {
(<FormArray>this.entryForm.get("childform")).push(this.initchildformForm());  }
onRemovechildform(index: number) {
(<FormArray>this.entryForm.get("childform")).removeAt(index);  }
 oneditchildform() {    this.childformcomponents.push({ 

 
active: "",
 

 
description: "",
 

 
name: "",
 


	  });  }  
 deletechildformRow(index) {
 this.childformcomponents.splice(index, 1); 
 }  
childformcomponents;
 // one to many end 

 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.supportcomponents = row.support;













this.childformcomponents = row.childform;


    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.onInputChangeaddition ('edit');
 //calculated field end

//calculated field start
	
this.onInputChangemultiplication ('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);


















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


















      }, (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;


















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

} 









  // calculated field code start 


 
 additionage; 
  

 
 additionage2; 
  


  additiontotal;
  additioncalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Addition"
  onInputChangeaddition(mode: 'add' | 'edit') {

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

 
      this.additionage2 = this.entryForm.value.age2 || '';
       


    } else {

 
      this.additionage = this.rowSelected.age;
 

 
      this.additionage2 = this.rowSelected.age2;
 

    }
    
 
    const ageValue = parseFloat(this.additionage) || 0;
     

 
    const age2Value = parseFloat(this.additionage2) || 0;
     

    switch (this.additioncalculateOperators) {
      case 'Addition':
        this.additiontotal = (
          
 
          ageValue +
           

 
          age2Value +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.additiontotal = (
          
 
          ageValue -
           

 
          age2Value -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.additiontotal = (
          
 
          ageValue *
           

 
          age2Value *
           

         1).toString();

        break;
      case 'Division':

        this.additiontotal = (
          
 
          ageValue /
           

 
          age2Value /
           

          1).toString();

        break;
      case 'Concatination':
        this.additiontotal = `
          
 
          ${this.additionage || ''}
           

 
          ${this.additionage2 || ''}
           

          ${lastObjstring || ''}`;

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



  // calculated field code start 


 
 multiplicationage; 
  

 
 multiplicationage2; 
  


  multiplicationtotal;
  multiplicationcalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Multiplication"
  onInputChangemultiplication(mode: 'add' | 'edit') {

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

 
      this.multiplicationage2 = this.entryForm.value.age2 || '';
       


    } else {

 
      this.multiplicationage = this.rowSelected.age;
 

 
      this.multiplicationage2 = this.rowSelected.age2;
 

    }
    
 
    const ageValue = parseFloat(this.multiplicationage) || 0;
     

 
    const age2Value = parseFloat(this.multiplicationage2) || 0;
     

    switch (this.multiplicationcalculateOperators) {
      case 'Addition':
        this.multiplicationtotal = (
          
 
          ageValue +
           

 
          age2Value +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.multiplicationtotal = (
          
 
          ageValue -
           

 
          age2Value -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.multiplicationtotal = (
          
 
          ageValue *
           

 
          age2Value *
           

         1).toString();

        break;
      case 'Division':

        this.multiplicationtotal = (
          
 
          ageValue /
           

 
          age2Value /
           

          1).toString();

        break;
      case 'Concatination':
        this.multiplicationtotal = `
          
 
          ${this.multiplicationage || ''}
           

 
          ${this.multiplicationage2 || ''}
           

          ${lastObjstring || ''}`;

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


//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('age').setValue(data.age);
							 


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

							
 
							this.rowSelected.age= data. age
							 


						}       });       this.valueListModalvalue_list_field =false;
						    }    //value List field end 

//Value List field start    
value_list_field2Mode;
searchcusttextvalue_list_field2 :any;    
 valueListModalvalue_list_field2 :boolean=false;
    openvalueListvalue_list_field2(mode){
 this.valueListModalvalue_list_field2=!this.valueListModalvalue_list_field2 ; 
      this.value_list_field2Mode = mode;     }
     customerdatavalue_list_field2 ;     
value_list_field2error;
clickedvalue_list_field2ID:number;

getcustvalue_list_field2ID(id:number){    
 this.clickedvalue_list_field2ID=id;
						    console.log("clicked by id"+ id);
						    this.mainService.getById(id).subscribe((data) => {       console.log(data);
						         if(this.value_list_field2Mode == "ADD"){ 

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

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

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


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

							
 
							this.rowSelected.name= data. name
							 

 
							this.rowSelected.age2= data. age2
							 

 
							this.rowSelected.age= data. age
							 


						}       });       this.valueListModalvalue_list_field2 =false;
						    }    //value List field end 



// updateaction
}

















