import {Directive, OnInit} from "@angular/core";
import {SearchCustomFilter} from "../../openaireLibrary/searchPages/searchUtils/searchUtils.class";
import {BaseComponent} from "../../openaireLibrary/sharedComponents/base/base.component";
import {CustomFilterService} from "../../openaireLibrary/shared/customFilter.service";
import {ActivatedRoute, Router} from "@angular/router";

@Directive()
export abstract class SearchBaseComponent extends BaseComponent implements OnInit {
  protected customFilterService: CustomFilterService;
  protected route: ActivatedRoute;
  protected router: Router;
  customFilters: SearchCustomFilter[];
  keyword = "";
  parameters = {};

  ngOnInit() {
    //for the case of national
    this.subscriptions.push((this.customFilterService.getCustomFilterAsObservable().subscribe(customFilters => {
      if (customFilters && customFilters.length > 0) {
        this.customFilters = customFilters;
        this.setStakeholderPrefixInMetadata();
      }
    })));
    this.subscriptions.push(this.route.params.subscribe(params => {
      if (params && params['stakeholder']) {

        this.subscriptions.push((this.customFilterService.getCustomFilterAsObservable().subscribe(customFilters => {
          if (customFilters && customFilters.length > 0) {
            this.customFilters = customFilters;
            this.setStakeholderPrefixInMetadata();
          }
        })));
      } else {
        // TODO
      }
    }));

    this.subscriptions.push(this.route.queryParams.subscribe(queryParams => {
      this.parameters = Object.assign({}, queryParams);
      this.keyword = (queryParams['keyword']) ? queryParams['keyword'] : (queryParams["q"] ? queryParams["q"] : (queryParams["f0"] && queryParams["f0"] == "q" && queryParams["fv0"] ? queryParams["fv0"] : ""));
    }));
  }

  search() {
    this.prepareKeywordParam(this.keyword);
    this.parameters["page"] = 1;
    this.router.navigate([location.pathname], {queryParams: this.parameters});
  }

  private prepareKeywordParam(keyword) {
    if (this.parameters["q"]) {
      delete this.parameters['q'];
      delete this.parameters['op'];
    }
    if (keyword.length > 0) {
      this.parameters["fv0"] = keyword;
      this.parameters["f0"] = "q";
    } else if (keyword.length == 0 && this.parameters["f0"] == "q") {
      delete this.parameters['f0'];
      delete this.parameters['fv0'];
    }
  }

  setStakeholderPrefixInMetadata(){
    this.title = (this.customFilters.length > 1?this.customFilters[1].valueName:this.customFilters[0].valueName) + " | ";
  }
}
