import {ChangeDetectorRef, Component} from "@angular/core";
import {
  MonitorIndicatorStakeholderBaseComponent
} from "../../openaireLibrary/monitor/monitor-indicator-stakeholder-base.component";
import {DomSanitizer, Meta, Title} from "@angular/platform-browser";
import {LayoutService} from "../../openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
import {StatisticsService} from "../../openaireLibrary/monitor-admin/utils/services/statistics.service";
import {StakeholderService} from "../../openaireLibrary/monitor/services/stakeholder.service";
import {UserManagementService} from "../../openaireLibrary/services/user-management.service";
import {IndicatorPath, Section, Visibility} from "../../openaireLibrary/monitor/entities/stakeholder";
import {ActivatedRoute, Router} from "@angular/router";
import {PiwikService} from "../../openaireLibrary/utils/piwik/piwik.service";
import {SEOService} from "../../openaireLibrary/sharedComponents/SEO/SEO.service";
import {SearchResearchResultsService} from "../../openaireLibrary/services/searchResearchResults.service";
import {CustomFilterService} from "../../openaireLibrary/shared/customFilter.service";
import {Dates, StringUtils} from "../../openaireLibrary/utils/string-utils.class";
import {Filter, Value} from "../../openaireLibrary/searchPages/searchUtils/searchHelperClasses.class";
import {SearchFields} from "../../openaireLibrary/utils/properties/searchFields";

@Component({
  selector: 'monitor',
  templateUrl: 'monitor.component.html'
})
export class MonitorComponent extends MonitorIndicatorStakeholderBaseComponent {
  activeChartSectionIndex: number = 0;

  constructor(protected _route: ActivatedRoute,
              protected _router: Router,
              protected _meta: Meta,
              protected _title: Title,
              protected _piwikService: PiwikService,
              protected seoService: SEOService,
              protected sanitizer: DomSanitizer,
              protected cdr: ChangeDetectorRef,
              protected layoutService: LayoutService,
              protected statisticsService: StatisticsService,
              protected searchResearchResultsService: SearchResearchResultsService,
              protected customFilterService: CustomFilterService,
              private userManagementService: UserManagementService,
              private stakeholderService: StakeholderService) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    this.minYear = Dates.yearMin;
    this.maxYear = Dates.yearMax;
    this.requireLogin = false;
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
      this.subscriptions.push(this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
        if (stakeholder) {
          this.loading = true;
          this.stakeholder = stakeholder;
          this.subscriptions.push(this.customFilterService.getCustomFilterAsObservable().subscribe(filters => {
            if (filters) {
              let customFilterParams = "";
              for (let customFilter of filters) {
                if (customFilter.isHiddenFilter) {
                  customFilterParams += "&fq=" + StringUtils.URIEncode(customFilter.queryFieldName + " exact " + StringUtils.quote((customFilter.valueId)));
                }
              }
              this.subscriptions.push(this.searchResearchResultsService.advancedSearchResults("publication", null, 1, 0, null, this.properties,
                "&refine=true&fields=fos&type=publications", ["fos"], customFilterParams).subscribe(res => {
                this.filters = this.postProcessingFosFilters(res[2]);
                this.title = this.stakeholder.name;
                this.description = this.stakeholder.name;
                this.subscriptions.push(this._route.params.subscribe(params => {
                  this.loading = true;
                  this.activeTopic = null;
                  this.activeCategory = null;
                  this.activeSubCategory = null;
                  this.numberResults = new Map<string, number>();
                  this.chartsActiveType = new Map<string, IndicatorPath>();
                  this.subscriptions.push(this._route.queryParams.subscribe(queryParams => {
                    this.handleQueryParams(queryParams, params);
                    this.setMetadata();
                  }));
                }));
              }));
            }
          }));
        }
      }));
    }));
  }

  hasPermission(visibility: Visibility): boolean {
    return true;
  }

  protected setIndicators() {
    this.activeChartSectionIndex = 0;
    super.setIndicators();
  }

  postProcessingFosFilters(refineFilters:Filter[]){
    let filters:Filter[] = [];
    for(let filter of refineFilters){
      if(filter.filterId == "fos"){
        let fos: Filter ={...filter};
        fos.values = [];
        for(let value of filter.values){
          let code = value.id.split(" ")[0];
          if(code.length <= 4){
            fos.values.push(value);
          }
        }
        fos.countAllValues = fos.values.length;
        filters.push(fos);
      }else{
        filters.push(filter);
      }
    }
    let publiclyFunded:Filter = new Filter();
    publiclyFunded.title =  "Publicly funded";

    publiclyFunded.type = "triplet";
    publiclyFunded.filterId =  "publiclyfunded";
  let searchFields: SearchFields = new SearchFields();
    let data = searchFields.RESULT_STATIC_FIELD_VALUES['publiclyfunded'];
    for(let i=0; i<data.length; i++) {
      var value:Value = new Value();
      value.name = data[i].name;
      value.number = 0
      value.id = data[i].id;
      //if(RefineResultsUtils.includeValue(value)){
      publiclyFunded.values.push(value);
      }

    publiclyFunded.type = "triplet";

    filters.push(publiclyFunded)
    return filters;
  }

  get tabs() {
    return this.activeSubCategory.charts.length > 1;
  }

  get chart(): Section {
    return this.activeSubCategory.charts[this.activeChartSectionIndex];
  }

  changeSection(index: number) {
    this.activeChartSectionIndex = index;
    this.cdr.detectChanges();
  }

  getSectionTitle(section: Section) {
    return section?.title?section.title.split('::')[0]:null;
  }

  getSectionDescription(section: Section) {
    return section?.title?section.title.split('::')[1]:null;
  }
}
