import { Component, Input, OnInit } from '@angular/core';
import {LocalQueryParameter, ParametricQuery} from 'src/app/models/enea/ParametricQuery';
import { Parameter } from 'src/app/models/Parameter';
import { DatasourceConfiguration } from 'src/app/widgets/Widget';
import { DataService } from 'src/app/services/data.service';
import { UtilsService } from 'src/app/services/utils.service';
import {ParameterResolverService} from "../../services/parameter-resolvers/parameter-resolver.service";

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

  @Input() datasourceConfiguration: DatasourceConfiguration;

  @Input() parametricQueries: ParametricQuery[] = [];
  @Input() showSelectDatasourceLabel: boolean = true;

  debug: Boolean = false;

  selectedQuery : ParametricQuery = new ParametricQuery();

  constructor(
        private dataService: DataService, 
        private utils: UtilsService, 
        private parameterResolver: ParameterResolverService) {
        this.datasourceConfiguration = new DatasourceConfiguration();
   }

  ngOnInit(): void {
    if (!this.datasourceConfiguration)
      this.datasourceConfiguration = new DatasourceConfiguration();
    if (this.parametricQueries.length === 0)
      this.loadParametricQueries();
  }

  loadParametricQueries() {
    this.dataService.getListOfFunctions().subscribe(
        parametricQueries => this.parametricQueries = parametricQueries,
        error => this.utils.showErrorMessage(error)
    );
  }

  updateParametricQueries(){
      this.parametricQueries = [];
      this.loadParametricQueries();
  }

  resetParameters() {
      if (this.datasourceConfiguration) {
      this.datasourceConfiguration.parameters = [];
      if (this.datasourceConfiguration.parametricQuery && this.datasourceConfiguration.parametricQuery.parameters) {
        this.datasourceConfiguration.parameters = this.datasourceConfiguration.parametricQuery.parameters.map(o => new Parameter(o.name || '', '', undefined));
        if (this.debug) this.utils.showErrorMessage("DatasourceConfiguration " + JSON.stringify(this.datasourceConfiguration));

      }
    }
  }

  updateQuery(query?: ParametricQuery){
    this.datasourceConfiguration!.parametricQuery = query;
    this.resetParameters();
  }

}
