import { Component, OnInit } from '@angular/core';


import { ToastrService } from 'ngx-toastr';
import { ActivatedRoute, Router } from '@angular/router';
import { College } from 'src/app/models/fnd/play';
import { student } from 'src/app/models/fnd/Studentadd';
import { AbstractControl,FormArray, FormBuilder, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { ValidationError } from 'src/app/models/fnd/ValidationError';
import { stepaservice } from './stepa.service';
declare var JsBarcode: any;
  @Component({
  selector: 'app-editstepper',
  templateUrl: './stepa.component.html',
  styleUrls: ['./stepa.component.scss']
})
export class stepaComponent implements OnInit {
  updated = false;
  stringJson: any;
  customerId: string = '';
  selectedFile!: File;
  fileName = '';

  id: number;
  errorFields: ValidationError[] = [];
  appToUpdate: College = null;
  trained = false;

  json: string = "";
  luisApp =
    {
      name: '',
      created: 1,
      trained: 1,
      tested: 1,
      updated: 1,
      published: 1,

    };
  // Layout direction changing
  layout = {
    direction: "vertical",
    block1: "clr-col-lg-3 clr-col-12 ",
    block2: "clr-col-lg-9 clr-col-12 ",
  };

  timelineStyle = { 
 step0: { state: "current", open: true, failed: false }, 
    step1: { state: "not-started", open: false, failed: false },
    step2: { state: "not-started", open: false, failed: false },
};
public SteperjjentryForm: FormGroup;
public TestlistentryForm: FormGroup;
  submitted = false;
  rowSelected: any = {};
  modalcomplete = false;

  constructor( 
private mainService: stepaservice,

private Steperjj_fb: FormBuilder, 
private Testlist_fb: FormBuilder, 
private router: Router,
 private route: ActivatedRoute,
    private toastr: ToastrService,
  ) { }

  ngOnInit(): void {
    this.id = this.route.snapshot.params["id"];
    console.log("update with id = ", this.id);


 this.SteperjjentryForm = this.Steperjj_fb.group({ 
names : [null],

 


  });

 this.getdatagrid_fieldData();


 this.TestlistentryForm = this.Testlist_fb.group({ 
name : [null],

country : [null],

countrydynamic : [null],


  });



this.getallcountrydynamic();


 const stepId = this.id; // or from route/query/etc
 
    this.getResolvedDataFromStepper(stepId).subscribe(res => {
      console.log('response get ', res);

      if (res === null) {
        this.showEmptyForm();
      } else {
 if (res['Steperjj']) {
 
 this.prefillonetestForm(res['Steperjj']);
        }

 if (res['Testlist']) {
 
 this.prefilltesttwoForm(res['Testlist']);
        }
}
    });

  }
showEmptyForm(): void {
    console.log('No config found. Showing empty form.');
    // You can choose to show one or both based on some logic

 this.SteperjjentryForm.reset();

 this.TestlistentryForm.reset();
  }  prefillonetestForm(data: any): void {

    console.log(' onetest data ', data)
    this.SteperjjentryForm.patchValue({
      id: data.id || '',
names: data.names || '',

datagrid_field: data.datagrid_field || '',

    });
  }  prefilltesttwoForm(data: any): void {

    console.log(' testtwo data ', data)
    this.TestlistentryForm.patchValue({
      id: data.id || '',
name: data.name || '',

country: data.country || '',

countrydynamic: data.countrydynamic || '',

    });
  }
 getResolvedDataFromStepper(id: number): Observable<any> {
    console.log('get step config');

    return new Observable(observer => {
      this.mainService.gettabledata(id).subscribe(configList => {
        if (!configList || configList.length === 0) {
          console.log('empty config');
          observer.next(null);
          observer.complete();
          return;
        }

        const results: { [key: string]: any } = {};
        let processed = 0;

        configList.forEach(config => {
          const { table_name, table_id } = config;

          this.getByTableNameAndId(table_name, table_id).subscribe(data => {

            console.log('data is ', data);
            results[table_name] = data;

            processed++;
            if (processed === configList.length) {
              observer.next(results);  // emit combined data
              observer.complete();
            }

          }, error => {
            console.error(`Error loading data for table ${table_name}`, error);
            processed++;
            if (processed === configList.length) {
              observer.next(results);  // continue with what we have
              observer.complete();
            }
          });
        });

      }, error => {
        console.error("Error loading stepper config", error);
        observer.error(error);
      });
    });
  }



  getByTableNameAndId(tableName: string, id: number): Observable<any> {

    switch (tableName) {
   case 'Steperjj':
        return this.mainService.getSteperjjById(id); case 'Testlist':
        return this.mainService.getTestlistById(id);// aur bhi cases agar naye table add ho to
      default:
        throw new Error(`Unknown table name: ${tableName}`);
    }
  }
  // Change to Horizontal Layout
  changeToHorizonTal() {
    this.layout = {
      direction: "horizontal",
      block1: "clr-col-lg-12 clr-col-12 height container",
      block2: "clr-col-lg-12 clr-col-12 container",
    }
  }
  // Change to Vertical Layout
  changeToVertical() {
    this.layout = {
      direction: "vertical",
      block1: "clr-col-lg-3 clr-col-12 ",
      block2: "clr-col-lg-9 clr-col-12 ",
    }
  }



  ononetestSave() {
    console.log('Form Submitted:', this.SteperjjentryForm.value);
    this.submitted = true;
    if (this.SteperjjentryForm.invalid) {

      console.log('invalid form ..');
      // Log all form errors
      Object.keys(this.SteperjjentryForm.controls).forEach(field => {
        const control = this.SteperjjentryForm.get(field);
        if (control && control.invalid) {
          console.log(`Error in field: ${field}`, control.errors);
        }
      }
      );
      return;
    }
    this.ononetestCreate();
  }

  ononetestCreate() {




    this.mainService.createSteperjj(this.SteperjjentryForm.value).subscribe(
      (data) => {
        console.log('adding data ', data);
        this.customerId = data.id;

        console.log('id is  ', this.customerId);


 const tableId = data.id;
        const tableName = 'Steperjj';
        const stepperId = this.id;

        // Save stepper config
        this.mainService.saveStepperConfig(stepperId, tableId, tableName).subscribe(() => {
          this.toastr.success("Stepper Config Saved");
        });        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");
        }
      });
    this.rowSelected = this.SteperjjentryForm.value;

    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }


  ontesttwoSave() {
    console.log('Form Submitted:', this.TestlistentryForm.value);
    this.submitted = true;
    if (this.TestlistentryForm.invalid) {

      console.log('invalid form ..');
      // Log all form errors
      Object.keys(this.TestlistentryForm.controls).forEach(field => {
        const control = this.TestlistentryForm.get(field);
        if (control && control.invalid) {
          console.log(`Error in field: ${field}`, control.errors);
        }
      }
      );
      return;
    }
    this.ontesttwoCreate();
  }

  ontesttwoCreate() {






    this.mainService.createTestlist(this.TestlistentryForm.value).subscribe(
      (data) => {
        console.log('adding data ', data);
        this.customerId = data.id;

        console.log('id is  ', this.customerId);


 const tableId = data.id;
        const tableName = 'Testlist';
        const stepperId = this.id;

        // Save stepper config
        this.mainService.saveStepperConfig(stepperId, tableId, tableName).subscribe(() => {
          this.toastr.success("Stepper Config Saved");
        });        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");
        }
      });
    this.rowSelected = this.TestlistentryForm.value;

    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }


  onnext() {
    this.router.navigate(["../../main/workflow"], { relativeTo: this.route });
  }
  reset() {
    this.json = "";
    this.luisApp =
    {
      name: '',
      trained: 1,
      tested: 1,
      updated: 1,
      published: 1,
      created: 1,

    };

    this.timelineStyle = {
      step0: { state: "current", open: true, failed: false },
      step1: { state: "not-started", open: false, failed: false },
      step2: { state: "not-started", open: false, failed: false },
 };
  }
  current() {
    console.log(this.timelineStyle)
    this.stringJson = JSON.stringify(this.timelineStyle);
    console.log("String json object :", this.stringJson);

  }


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





selectcountrydynamic ;     
getallcountrydynamic() {
 this.mainService.getAllcountrydynamic().subscribe(data=>{
this.selectcountrydynamic = data;       
console.log(data);
},(error) => {       console.log(error);     });   }							   











// updateaction
}









