import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { ReportBuilderService } from 'src/app/services/api/report-builder.service';
import { SureconnectService } from '../../dashboardnew/sureconnect/sureconnect.service';


@Component({
  selector: 'app-report-build2edit',
  templateUrl: './report-build2edit.component.html',
  styleUrls: ['./report-build2edit.component.scss']
})
export class ReportBuild2editComponent implements OnInit {
  public entryForm: FormGroup;
  updated = false;
  ReportData: any = {};
  id: number;
  nodeEditProperties = {
    std_param_html: '',
    adhoc_param_html: '',
    // column_str:'',
    // conn_name:'',
    date_param_req: '',
    // folderName:'',
    url: '',
    // Add sureConnectId property
    sureConnectId: null,

  };
  // Add sureconnect data property
  sureconnectData: any[] = [];

  constructor(private router: Router,
    private route: ActivatedRoute, private reportBuilderService: ReportBuilderService,
    private toastr: ToastrService, private _fb: FormBuilder,
    private sureconnectService: SureconnectService) { }

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

    this.entryForm = this._fb.group({
      std_param_html: [null],
      adhoc_param_html: [null],
      // column_str:[null],
      // conn_name:[null],
      date_param_req: [null],
      // folderName:[null],
      url: [null],
      // Add sureConnectId to form
      sureConnectId: [null],
    });

    // Load sureconnect data first, then load report data
    this.loadSureconnectData();
    this.getById(this.id);
    this.listoddatabase();
  }

  // Add method to load sureconnect data
  loadSureconnectData() {
    this.sureconnectService.getAll().subscribe((data: any[]) => {
      this.sureconnectData = data;
      console.log('Sureconnect data loaded:', this.sureconnectData);
    }, (error) => {
      console.log('Error loading sureconnect data:', error);
    });
  }

  databaselist;
  listoddatabase() {
    this.reportBuilderService.getdatabse().subscribe((data) => {
      this.databaselist = data;
      console.log(this.databaselist)
    }, (error) => {
      console.log(error);
      if (error) {
      }
    });

  }
  builderLine;
  lineId;
  builderLineData: any[] = [];
  getById(id: number) {
    this.reportBuilderService.getrbDetailsById(id).subscribe(
      (data) => {
        console.log(data);
        this.ReportData = data;


        this.builderLine = this.ReportData.rpt_builder2_lines;
        this.lineId = this.builderLine[0].id
        console.log("line data ", this.lineId, this.builderLine);
        if (this.builderLine[0].model != '') {
          this.builderLineData = JSON.parse(this.builderLine[0].model);
          console.log(this.builderLineData);

          this.nodeEditProperties.std_param_html = this.builderLineData[0].std_param_html;
          this.nodeEditProperties.adhoc_param_html = this.builderLineData[0].adhoc_param_html;
          // this.nodeEditProperties.column_str = this.builderLineData.column_str;
          // this.nodeEditProperties.conn_name = this.builderLineData.conn_name;
          this.nodeEditProperties.date_param_req = this.builderLineData[0].date_param_req;
          this.nodeEditProperties.url = this.builderLineData[0].url;
          // Set sureConnectId if it exists in the data
          this.nodeEditProperties.sureConnectId = this.builderLineData[0].sureConnectId || null;

          // Update form with loaded data
          this.entryForm.patchValue(this.nodeEditProperties);
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  stdparams;
  keysfromurl;
  getkeys() {
    if (this.nodeEditProperties.url !== null) {
      this.reportBuilderService.getcolumnDetailsByurl(this.nodeEditProperties.url).subscribe(data => {
        console.log('coloum list data ', data);
        this.keysfromurl = data;
        this.nodeEditProperties.adhoc_param_html = this.keysfromurl;
      })
    } else {
      this.toastr.error("URL is required");
    }
  }


  listBuilder_Lines = {
    model: {}
  }
  update() {


    this.builderLineData[0] = {
      std_param_html: this.nodeEditProperties.std_param_html,
      adhoc_param_html: this.nodeEditProperties.adhoc_param_html,
      date_param_req: this.nodeEditProperties.date_param_req,
      url: this.nodeEditProperties.url,
      // Add sureConnectId to the data
      sureConnectId: this.nodeEditProperties.sureConnectId,
    };

    this.builderLineData[0].std_param_html = this.nodeEditProperties.std_param_html;
    this.builderLineData[0].adhoc_param_html = this.nodeEditProperties.adhoc_param_html;
    //  this.builderLineData.column_str =  this.nodeEditProperties.column_str;
    //  this.builderLineData.conn_name = this.nodeEditProperties.conn_name ;
    this.builderLineData[0].date_param_req = this.nodeEditProperties.date_param_req;
    this.builderLineData[0].url = this.nodeEditProperties.url;
    // Add sureConnectId to the data
    this.builderLineData[0].sureConnectId = this.nodeEditProperties.sureConnectId;

    console.log(this.builderLineData);
    // this.builderLineData.splice(1);
    console.log(this.builderLineData);
    let tmp = JSON.stringify(this.builderLineData); //.replace(/\\/g, '')
    this.listBuilder_Lines.model = tmp;
    console.log(this.listBuilder_Lines);

    this.reportBuilderService.updaterbLineData(this.listBuilder_Lines, this.lineId).subscribe(
      (data) => {
        console.log(data);
        if (data) {
          this.toastr.success('Update successfully');
        }
        this.router.navigate(["../../all"], { relativeTo: this.route });
        //this.router.navigate(["../../all"],{ relativeTo: this.route, queryParams: { p_id: this.projectId } });
      },
      (error) => {
        console.log(error); // this will come from backend
      }
    );
    // this.lineBuilder_Header = new Rn_Cff_ActionBuilder_Header();
  }

  onSubmit() {
    this.updated = true;
    // Update nodeEditProperties with form values including sureConnectId
    Object.assign(this.nodeEditProperties, this.entryForm.value);
    this.update();
  }

  back() {
    this.router.navigate(["../../all"], { relativeTo: this.route });
  }

}   