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

selectstatic : [null],

selectstaticmul : [null],

selectdynamic : [null],

selectdynamicmul : [null],

selectautocom : [null],

selectautomul : [null],



child: this.initLinesForm(),

 


 



















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

this.getallselectdynamicmul();

this.getallselectautocom();

this.getallselectautomul();








  }

















initLinesForm() {   return this._fb.group({

 
  names: [null],
 
		

});   } 
		



 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.nodeEditPropertiesselectstaticmul.editselectedAttributesselectstaticmul = JSON.parse(this.rowSelected.selectstaticmul );



this.nodeEditPropertiesselectdynamicmul.editselectedAttributesselectdynamicmul = JSON.parse(this.rowSelected.selectdynamicmul );



this.nodeEditPropertiesselectautomul.editselectedAttributesselectautomul = JSON.parse(this.rowSelected.selectautomul );








    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;




this.rowSelected.selectstaticmul  = JSON.stringify(this.nodeEditPropertiesselectstaticmul.editselectedAttributesselectstaticmul  );



this.rowSelected.selectdynamicmul  = JSON.stringify(this.nodeEditPropertiesselectdynamicmul.editselectedAttributesselectdynamicmul  );



this.rowSelected.selectautomul  = JSON.stringify(this.nodeEditPropertiesselectautomul.editselectedAttributesselectautomul  );







    //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.entryForm.value.selectstaticmul  = JSON.stringify(this.nodeEditPropertiesselectstaticmul.addselectedAttributesselectstaticmul );



this.entryForm.value.selectdynamicmul  = JSON.stringify(this.nodeEditPropertiesselectdynamicmul.addselectedAttributesselectdynamicmul );



this.entryForm.value.selectautomul  = JSON.stringify(this.nodeEditPropertiesselectautomul.addselectedAttributesselectautomul );







  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;







this.nodeEditPropertiesselectdynamicmul.addselectedAttributesselectdynamicmul = ""



this.nodeEditPropertiesselectautomul.addselectedAttributesselectautomul = ""





 this.getdatagrid_fieldData();


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

} 




nodeEditPropertiesselectstaticmul  = {   addselectedAttributesselectstaticmul :"",   editselectedAttributesselectstaticmul :"" }
							 selectselectstaticmul =[
								
 
								's',
								 

 
								'l',
								 

 
								'n',
								 

							];

selectselectdynamic ;     
getallselectdynamic() {
 this.mainService.getAllselectdynamic().subscribe(data=>{
this.selectselectdynamic = data;       
console.log(data);
},(error) => {       console.log(error);     });   }							   

selectselectdynamicmul;    
 getallselectdynamicmul () {
		this.mainService.getAllselectdynamicmul().subscribe(data=>{
							      this.selectselectdynamicmul = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesselectdynamicmul  = {     addselectedAttributesselectdynamicmul:"",  editselectedAttributesselectdynamicmul :""   }

selectselectautocom ;    
 getallselectautocom () {
							    this.mainService.getAllselectautocom().subscribe(data=>{
							      this.selectselectautocom = data;       console.log(data);
							    },(error) => {       console.log(error);     });   }

selectselectautomul;    
 getallselectautomul () {
		this.mainService.getAllselectautomul().subscribe(data=>{
							      this.selectselectautomul = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesselectautomul  = {     addselectedAttributesselectautomul:"",  editselectedAttributesselectautomul :""   }





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

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


}
















