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


  public UpdateFormButtonUpdate: 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],





support: this.supportinitLinesForm(),

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


 









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

  // Update code end

// inser code start
  this.UpdateFormButtonUpdate = this._fb.group({
    description: '',
    name: '',
  });

  // Update 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 === "Ad8_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);
    }
  }






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

 
  description: [null],
 

 
  name: [null],
 
		

});   } 
		

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










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

} 










// updateaction

// update button


modalUpdateButtonupdate2 = false; 
goToUpdateButtonupdate2() {
  this.modalUpdateButtonupdate2=true;
  }
onSubmitUpdateButtonupdate2(id) {
  console.log(this.UpdateFormButtonupdate2.value);
  this.submitted=true;
  if (this.UpdateFormButtonupdate2.invalid) {
    return;
  }
  this.onUpdateButtonupdate2(id);
}
onUpdateButtonupdate2(id) {
    this.modalUpdateButtonupdate2=false;
   this.mainService.updateChildform(id,this.UpdateFormButtonupdate2.value).subscribe(data => {
     console.log(data)
     if (data.status >=200 && data.status <=209) {
      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.UpdateFormButtonupdate2.reset();
 }
//  update buuton code end



// update button


modalUpdateButtonUpdate = false; 
goToUpdateButtonUpdate() {
  this.modalUpdateButtonUpdate=true;
  }
onSubmitUpdateButtonUpdate(id) {
  console.log(this.UpdateFormButtonUpdate.value);
  this.submitted=true;
  if (this.UpdateFormButtonUpdate.invalid) {
    return;
  }
  this.onUpdateButtonUpdate(id);
}
onUpdateButtonUpdate(id) {
    this.modalUpdateButtonUpdate=false;
   this.mainService.updateSupport(id,this.UpdateFormButtonUpdate.value).subscribe(data => {
     console.log(data)
     if (data.status >=200 && data.status <=209) {
      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.UpdateFormButtonUpdate.reset();
 }
//  update buuton code end


}



