import {ChangeDetectorRef, Component} from '@angular/core';
import {PluginBaseComponent, PluginBaseInfo} from "../../utils/base-plugin.component";
import {ConfigurationService} from '../../../../../openaireLibrary/utils/configuration/configuration.service';
import {CommunityService} from '../../../../../openaireLibrary/connect/community/community.service';
import {SearchCommunityProjectsService} from '../../../../../openaireLibrary/connect/projects/searchProjects.service';
import {SearchCommunityDataprovidersService} from '../../../../../openaireLibrary/connect/contentProviders/searchDataproviders.service';
import {ZenodoCommunitiesService} from '../../../../../openaireLibrary/connect/zenodoCommunities/zenodo-communities.service';
import {User} from '../../../../../openaireLibrary/login/utils/helper.class';
import {RouterHelper} from "../../../../utils/routerHelper.class";
import {OpenaireEntities} from "../../../../utils/properties/searchFields";
import {HttpClient} from "@angular/common/http";
import {Filter} from "../../../../searchPages/searchUtils/searchHelperClasses.class";
import {Router} from "@angular/router";
import {SearchResearchResultsService} from "../../../../services/searchResearchResults.service";
import {CustomizationService} from "../../../../services/customization.service";

export class PluginGatewayInformation extends PluginBaseInfo{
  showTitle:boolean = true;
  showShortTitle:boolean = false;
  description:boolean = false;
  sdgs:boolean = false;
  fos:boolean = false;
  searchbar:boolean = false;
  title:string ="Gateway Information";
  curators:boolean = true;
  date:boolean = true;
  communities:boolean = true;
  projects:boolean = true;
  organizations:boolean = true;
  datasources:boolean = true;
  subjects:boolean = true;
  publications:boolean = true;
  datasets:boolean = true;
  software:boolean = true;
  other:boolean = true;

  compare(oldObject): any {
    let newObj=   super.compare(oldObject);
    return newObj;
  }
}
@Component({
  selector: 'plugin-gateway-information',
  templateUrl: 'plugin-gateway-information.component.html',
  styleUrls: ['plugin-gateway-information.component.less']
})
export class PluginGatewayInformationComponent extends PluginBaseComponent<PluginGatewayInformation>{
  default = new PluginGatewayInformation();
  community = null;
  portal = null;
  params: any = {};

  projectTotal = null;
  contentProviderTotal = null;
  projectsCalculated: boolean = false;
  contentProvidersCalculated: boolean = false;
  zenodoCommunityIdS = [];
  masterZenodoCommunity = null;

  searchLinkToProjects: string = null;
  searchLinkToDataProviders: string = null;
  shareInZenodoPage: string = null;

  displayedAllSubjects = [];
  displayedSubjects = [];
  displayedSdg = [];
  displayedFos = [];
  resultCounts = null;
  private user: User;
  searchLinkToResults: string = null;
  public routerHelper: RouterHelper = new RouterHelper();
  openaireEntities= OpenaireEntities;

  selectedEntity = 'result';
  selectedEntitySimpleUrl;
  selectedEntityAdvancedUrl;
  resultTypes: Filter = {
    values: [],
    filterId: "type",
    countSelectedValues: 0,
    filterType: 'checkbox',
    originalFilterId: "",
    valueIsExact: true,
    title: "Type",
    filterOperator: "or"
  };

  keyword: string = "";
  // customFilter;
  placeholderText = "Search by title, author, abstract, DOI, orcid... ";
  resultsQuickFilter: { filter: Filter, selected: boolean, filterId: string, value: string } = {
    filter: null,
    selected: true,
    filterId: "resultbestaccessright",
    value: "Open Access"
  };
  disableSelect: boolean = true;
  constructor(private http:HttpClient,
              private config: ConfigurationService,
              private communityService: CommunityService, 
              private searchCommunityProjectsService: SearchCommunityProjectsService,
              private searchCommunityDataprovidersService: SearchCommunityDataprovidersService,
              private zenodoCommunitiesService: ZenodoCommunitiesService, private _router: Router,
              private _searchResearchResultsService: SearchResearchResultsService,
              private cdr: ChangeDetectorRef, protected layoutService: CustomizationService) {
    super();
    this.searchLinkToResults = this.properties.searchLinkToResults;
    this.searchLinkToProjects = this.properties.searchLinkToProjects;
    this.searchLinkToDataProviders = this.properties.searchLinkToDataProviders;
    this.shareInZenodoPage = this.properties.shareInZenodoPage;

    this.subscriptions.push(this.config.portalAsObservable.subscribe(
      res => {
        this.portal = res;
      },
      error => {
        console.log(error);
      }
    ));
    this.subscriptions.push(this.communityService.getCommunityAsObservable().subscribe(
      community => {
        this.community = community;
        if (community) {
          this.displayedSubjects = community.subjects;
          this.displayedSdg = community.sdg;
          this.displayedFos = community.fos;
          this.displayedSubjects.forEach(element => {
            this.displayedAllSubjects.push({value: element, type: 'resultsubject'});
          });
          this.displayedSdg.forEach(element => {
            this.displayedAllSubjects.push({value: element, type: 'sdg'});
          });
          this.displayedFos.forEach(element => {
            this.displayedAllSubjects.push({value: element, type: 'fos'});
          });
          if (this.properties.environment == "development") {
            this.params = {communityId: community.communityId};
          }
          if (this.community.zenodoCommunity) {
            this.subscriptions.push(this.zenodoCommunitiesService.getZenodoCommunityById(this.properties, this.community.zenodoCommunity).subscribe(
              res => {
                this.masterZenodoCommunity = res;
              },
              error => {
                console.log(error);
              }
            ));
          }
          this.zenodoCommunityIdS = this.community.otherZenodoCommunities;

          // Double check below: is `this.community.communityId` correct? the other way was through @input communityID from ConnectHelper service - domain
          this.subscriptions.push(this.searchCommunityProjectsService.countTotalProjects(this.properties, this.community.communityId).subscribe(
            res => {
              this.projectTotal = res;
            },
            error => {
              console.log(error);
            },
            () => {
              this.projectsCalculated = true;
            }
          ));
          // Double check below: is `this.community.communityId` correct? the other way was through @input communityID from ConnectHelper service - domain
          this.subscriptions.push(this.searchCommunityDataprovidersService.countTotalDataproviders(this.properties, this.community.communityId).subscribe(
            res => {
              this.contentProviderTotal = res;
            },
            error => {
              console.log(error);
            },
            () => {
              this.contentProvidersCalculated = true;
            }
          ));
          this.subscriptions.push(this._searchResearchResultsService.countResults("communityid", this.community.communityId).subscribe(res => {
            this.resultCounts = res;
          }));
        }
      }
    ));

  }

  ngOnInit() {
    if (this.community) {
      this.getLayout(this.community.communityId);
    }
  }
  isEntityEnabled(entity: string) {
    return this.portal.entities.some(x => x['pid'] == entity && x['isEnabled'] === true);
  }

  isRouteEnabled(route: string) {
    return this.portal && this.portal.pages.some(x => x['route'] == route && x['isEnabled'] === true);
  }

  buildProjectsTooltip(): string {
    let tooltipContent: string = "<div>";

    if (this.projectTotal != null && this.projectTotal > 0 && this.isEntityEnabled('project') && this.isRouteEnabled(this.searchLinkToProjects)) {
      tooltipContent += "<span class='uk-text-bold'>Projects</span>";
    }

    tooltipContent += " have been selected as relevant for your community by the gateway curators.";
    tooltipContent += "</div>";

    return tooltipContent;
  }

  public buildContentProvidersTooltip(): string {
    let tooltipContent: string = "<div>";
    
    if (this.contentProviderTotal != null && this.contentProviderTotal > 0 && this.isEntityEnabled('datasource') && this.isRouteEnabled(this.searchLinkToDataProviders)) {
      tooltipContent += "<span class='uk-text-bold'>Content Providers</span>";
    }

    tooltipContent += " have been selected as relevant for your community by the gateway curators.";
    tooltipContent += "</div>";

    return tooltipContent;
  }

  public buildZenodoCommunitiesTooltip(): string {
    let tooltipContent: string = "<div>";

    tooltipContent += "<span class='uk-text-bold'>Zenodo</span> is a catch-all repository for OpenAIRE.";
    tooltipContent += "<div class='uk-margin-small-top'>A <span class='uk-text-bold'>Zenodo Community</span> is created and curated by Zenodo users.</div>";
    tooltipContent += "</div>";
    
    return tooltipContent;
  }
  public getParamsForSearchLink(type: string = "") {
    if (type) {
      return this.routerHelper.createQueryParams(['type', 'qf', 'sortBy'], [type, 'false', 'resultdateofacceptance,descending']);
    } else {
      return {};
    }
  }


  entityChanged($event) {
    this.selectedEntity = $event.entity;
    this.selectedEntitySimpleUrl = $event.simpleUrl;
    this.selectedEntityAdvancedUrl = $event.advancedUrl;
    if (this.selectedEntity == 'result') {
      this.placeholderText = "Search by title, author, abstract, DOI, orcid... ";
    } else if (this.selectedEntity == 'project') {
      this.placeholderText = "Search by project title, grant id, funder...";
    } else if (this.selectedEntity == 'dataprovider') {
      this.placeholderText = "Search by name...";
    } else {
      this.placeholderText = "Search community content";
    }
  }

  goTo(simple: boolean) {
    let url = (simple) ? this.selectedEntitySimpleUrl : this.selectedEntityAdvancedUrl;
    let parameterNames = [];
    let parameterValues = [];

    if (this.selectedEntity == "result" && this.resultsQuickFilter && this.resultsQuickFilter.selected) {
      parameterNames.push(this.resultsQuickFilter.filterId);
      parameterValues.push('"'+ encodeURIComponent(this.resultsQuickFilter.value)+'"');
    }

    if (this.keyword.length > 0) {
      parameterNames.push("fv0");
      parameterValues.push(this.keyword);
      parameterNames.push("f0");
      parameterValues.push("q");
    }
    this._router.navigate([url], {queryParams: this.routerHelper.createQueryParams(parameterNames, parameterValues)});
  }

  disableSelectChange(event: boolean) {
    this.disableSelect = event;
    this.cdr.detectChanges();
  }

}
