import {Component, EventEmitter, Input, Output, ViewChild} from '@angular/core';
import {EnvProperties} from "../../utils/properties/env-properties";
import {SearchCustomFilter} from "./searchUtils.class";
import {ConfigurationService} from "../../utils/configuration/configuration.service";
import {Router} from "@angular/router";
import {Subscription} from "rxjs";
import {properties} from '../../../../environments/environment';
import {InputComponent, Option} from "../../sharedComponents/input/input.component";
import {OpenaireEntities} from "../../utils/properties/searchFields";

@Component({
  selector: 'entities-selection',
  template: `
    <ng-container *ngIf="simpleView && entities.length > 0">
      <div #input input placeholder="Type" hint="What type of content?" inputClass="advanced-search" [selectArrow]="null"
           [options]="entities" [(value)]="selectedEntity" (valueChange)="entityChanged()" type="select"></div>
    </ng-container>
    <ng-container *ngIf="!simpleView && entities.length > 0">
      <div #input input inputClass="inner small"
           [options]="entities" [(value)]="selectedEntity" (valueChange)="entityChanged()" type="select"></div>
    </ng-container>
  `
})
export class EntitiesSelectionComponent {
  @Input() onlyresults: boolean = false;
  @Input() customFilter: SearchCustomFilter = null;
  @Input() selectedEntity = "result";
  @Input() currentEntity = "result";
  @Input() simpleView: boolean = true;
  @Input() onChangeNavigate: boolean = true;
  @Output() selectionChange = new EventEmitter();
  @ViewChild('input') input: InputComponent;
  @Output() disableSelectEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();
  public entities: Option[] = [];
  public properties: EnvProperties = properties;
  private subscriptions: Subscription[] = [];
  
  constructor(private config: ConfigurationService, private router: Router) {
  }
  
  /** TODO change conditions base on PortalType instead of customFilter */
  ngOnInit() {
    if ((this.customFilter && this.customFilter.queryFieldName == "communityId") || (['explore', 'aggregator', 'eosc', 'faircore4eosc'].includes(this.properties.adminToolsPortalType))) {
      this.subscriptions.push(this.config.portalAsObservable.subscribe(data => {
        if (data) {
          let showEntity = {};
          let showPage = {};
          if (data['entities']) {
            for (let i = 0; i < data['entities'].length; i++) {
              
              showEntity["" + data['entities'][i]["pid"] + ""] = data['entities'][i]["isEnabled"];
            }
          }
          if (data['pages']) {
            for (let i = 0; i < data['pages'].length; i++) {
              showPage["" + data['pages'][i]["route"] + ""] = data['pages'][i]["isEnabled"];
            }
          }
          this.entities = [];
          if(this.onlyresults) {
            if(this.simpleView) {
              this.entities.push({label: 'All ' + OpenaireEntities.RESULTS.toLowerCase(), value: 'all'});
            }
            if(showPage[this.simpleView ? this.properties.searchLinkToResults : this.properties.searchLinkToAdvancedResults] && showEntity["publication"]) {
              this.entities.push({label: OpenaireEntities.PUBLICATIONS, value: 'publications'});
            }
            if(showPage[this.simpleView ? this.properties.searchLinkToResults : this.properties.searchLinkToAdvancedResults] && showEntity["dataset"]) {
              this.entities.push({label: OpenaireEntities.DATASETS, value: 'datasets'});
            }
            if(showPage[this.simpleView ? this.properties.searchLinkToResults : this.properties.searchLinkToAdvancedResults] && showEntity["software"]) {
              this.entities.push({label: OpenaireEntities.SOFTWARE, value: 'software'});
            }
            if(showPage[this.simpleView ? this.properties.searchLinkToResults : this.properties.searchLinkToAdvancedResults] && showEntity["orp"]) {
              this.entities.push({label: OpenaireEntities.OTHER, value: 'other'});
            }
          } else {
            if(this.simpleView) {
              this.entities.push({label: 'All Content', value: 'all'});
            }
            if(showPage[this.simpleView ? this.properties.searchLinkToResults : this.properties.searchLinkToAdvancedResults]
              && (showEntity["publication"] || showEntity["dataset"] || showEntity["software"] || showEntity["orp"])) {
              this.entities.push({label: OpenaireEntities.RESULTS, value: 'result', tooltip: OpenaireEntities.RESULTS+' ('+OpenaireEntities.PUBLICATIONS.toLowerCase()+', '+OpenaireEntities.DATASETS.toLowerCase()+', '+OpenaireEntities.SOFTWARE.toLowerCase()+', '+OpenaireEntities.OTHER.toLowerCase()+')'});
            }
            if(showPage[this.simpleView ? this.properties.searchLinkToProjects : this.properties.searchLinkToAdvancedProjects] && showEntity["project"]) {
              this.entities.push({label: OpenaireEntities.PROJECTS, value: 'project'});
            }
            if(showPage[this.simpleView ? this.properties.searchLinkToOrganizations : this.properties.searchLinkToAdvancedOrganizations] && showEntity["organization"]) {
              this.entities.push({label: OpenaireEntities.ORGANIZATIONS, value: 'organization'});
            }
            if(showPage[this.simpleView ? this.properties.searchLinkToDataProviders : this.properties.searchLinkToAdvancedDataProviders] && showEntity["datasource"]) {
              this.entities.push({label: OpenaireEntities.DATASOURCES, value: 'dataprovider'});
            }
              if (showPage[this.simpleView ? this.properties.searchLinkToServices : this.properties.searchLinkToAdvancedServices] && showEntity["service"]) {
              this.entities.push({label: OpenaireEntities.SERVICES, value: 'service'});
            }
          }
          if (this.customFilter && this.customFilter.queryFieldName == "communityId" || this.properties.adminToolsCommunity === "connect") {
            //for community pages: no organization in simple search, only results in advanced
            this.entities = this.entities.filter(option => option.value !== 'organization' && option.value !== 'all');
            if (!this.simpleView) {
              this.entities = this.entities.filter(option => option.value !== 'project' && option.value !== 'dataprovider' && option.value !== 'service');
            }
          }
          this.disableSelectEmitter.emit(this.entities.length == 1);
        }
      }));
    } else if ((this.customFilter && this.customFilter.queryFieldName == "community") ||
      (this.customFilter && (this.customFilter.queryFieldName == "relfunder" || this.customFilter.queryFieldName == "funder")) ||
      (this.customFilter && this.customFilter.queryFieldName == "relorganizationid")
    || this.properties.dashboard == "irish") {
      this.entities.push({label: OpenaireEntities.RESULTS, value: 'result'});
      this.entities.push({label: OpenaireEntities.PROJECTS, value: 'project'});
      this.entities.push({label: OpenaireEntities.ORGANIZATIONS, value: 'organization'});
      this.entities.push({label: OpenaireEntities.DATASOURCES, value: 'dataprovider'});
      this.entities.push({label: OpenaireEntities.SERVICES, value: 'service'});
      this.disableSelectEmitter.emit(true);
    } else {
      if(this.onlyresults) {
        if(this.simpleView) {
          this.entities.push({label: 'All ' + OpenaireEntities.RESULTS.toLowerCase(), value: 'all'});
        }
        this.entities.push({label: OpenaireEntities.PUBLICATIONS, value: 'publications'});
        this.entities.push({label: OpenaireEntities.DATASETS, value: 'datasets'});
        this.entities.push({label: OpenaireEntities.SOFTWARE, value: 'software'});
        this.entities.push({label: OpenaireEntities.OTHER, value: 'other'});
      } else {
        if(this.simpleView) {
          this.entities.push({label: 'All Content', value: 'all'});
        }
        this.entities.push({label: OpenaireEntities.RESULTS, value: 'result'});
        this.entities.push({label: OpenaireEntities.PROJECTS, value: 'project'});
        this.entities.push({label: OpenaireEntities.ORGANIZATIONS, value: 'organization'});
        this.entities.push({label: OpenaireEntities.DATASOURCES, value: 'dataprovider'});
        this.entities.push({label: OpenaireEntities.SERVICES, value: 'service'});
        this.disableSelectEmitter.emit(false);
      }
    }
    this.selectedEntity = this.currentEntity;
    this.selectionChange.emit({
      init: true,
      entity: this.selectedEntity,
      simpleUrl: this.getUrl(true),
      advancedUrl: this.getUrl(false)
    });
  }
  
  public ngOnDestroy() {
    for (let subscription of this.subscriptions) {
      subscription.unsubscribe();
    }
  }
  
  getLabel(value: string) {
    return this.entities.find(entity => entity.value === value)?.label;
  }
  
  entityChanged() {
    if (!this.simpleView || this.onChangeNavigate) {
      this.router.navigate([this.getUrl(this.simpleView)], {queryParams: this.customFilter ? this.customFilter.getParameters() : {}});
    } else {
      this.selectionChange.emit({
        entity: this.selectedEntity,
        simpleUrl: this.getUrl(true),
        advancedUrl: this.getUrl(false)
      });
    }
    
  }
  
  getUrl(simpleView: boolean): string {
    if (!this.onlyresults) {
      if (this.selectedEntity == "all") {
        return (simpleView ? "/search/find/" : null);
      } else if (this.selectedEntity == "result") {
        return (simpleView ? this.properties.searchLinkToResults : this.properties.searchLinkToAdvancedResults);
      } else if (this.selectedEntity == "project") {
        return (simpleView ? this.properties.searchLinkToProjects : this.properties.searchLinkToAdvancedProjects);
      } else if (this.selectedEntity == "dataprovider") {
        return (simpleView ? this.properties.searchLinkToDataProviders : this.properties.searchLinkToAdvancedDataProviders);
      } else if (this.selectedEntity == "service") {
        return (simpleView ? this.properties.searchLinkToServices : this.properties.searchLinkToAdvancedServices);
      } else if (this.selectedEntity == "organization") {
        return (simpleView ? this.properties.searchLinkToOrganizations : this.properties.searchLinkToAdvancedOrganizations);
      }
    } else {
      return (simpleView ? this.properties.searchLinkToResults : this.properties.searchLinkToAdvancedResults);
    }
  }
}
