import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Metadata, ParametricQuery} from 'src/app/models/enea/ParametricQuery';
import {TableWidget} from 'src/app/widgets/table/models/TableWidget';
import {DataService} from 'src/app/services/data.service';
import {UtilsService} from 'src/app/services/utils.service';
import {DatasourceConfiguration, Widget} from "../../../Widget";
import {WidgetService} from "../../../../services/widget.service";

@Component({
  selector: 'app-table-widget-configuration',
  templateUrl: './table-widget-configuration.component.html',
  styleUrls: ['./table-widget-configuration.component.css']
})
export class TableWidgetConfigurationComponent implements OnInit {

  @Input() widget?: TableWidget;
   public parametricQueries: ParametricQuery[] = [];

  constructor(private widgetService: WidgetService,
              private dataService: DataService,
              private utils: UtilsService) {
  }

  ngOnInit(): void {
    // if (this.widget && !this.widget?.datasourceConfiguration)
    //  this.widget.datasourceConfiguration = new DatasourceConfiguration();

    // FIX prime ng bug: when options has just 1 column
    // is not selected in [(ngModel)]
    //this.selectFirstColumnIfNoColumnIsSelected();
    this.loadParametricQueries();
  }

  private selectFirstColumnIfNoColumnIsSelected() {
    if (this.widget?.datasourceConfiguration?.parametricQuery?.metadata &&
        this.widget.datasourceConfiguration.parametricQuery.metadata.length > 0 &&
        this.widget?.rowSelectable && !this.widget.rowSelectColumn) {
      this.widget.rowSelectColumn = this.widget.datasourceConfiguration.parametricQuery.metadata[0].name;
    }
  }


  loadParametricQueries() {
    this.dataService.getListOfFunctions().subscribe(
        parametricQueries => this.parametricQueries = parametricQueries,
        error => this.utils.showErrorMessage(error)
    );
  }
 // configurationChanged() {
  //  this.widgetService.onConfigurationChanged.next(this.widget);
  //}
}
