import {Component, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

import {ErrorCodes} from '../../openaireLibrary/utils/properties/errorCodes';
import {ErrorMessagesComponent} from '../../openaireLibrary/utils/errorMessages.component';
import {SearchFields} from '../../openaireLibrary/utils/properties/searchFields';
import {SearchCustomFilter, SearchUtilsClass} from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';
import {
  SearchCommunityDataprovidersService
} from '../../openaireLibrary/connect/contentProviders/searchDataproviders.service';
import {properties} from "../../../environments/environment";
import {CommunitiesService} from "../../openaireLibrary/connect/communities/communities.service";
import {CommunityService} from "../../openaireLibrary/connect/community/community.service";
import {Subscriber} from "rxjs";
import {AdvancedField} from "../../openaireLibrary/searchPages/searchUtils/searchHelperClasses.class";
import {NewSearchPageComponent} from "../../openaireLibrary/searchPages/searchUtils/newSearchPage.component";
import {SearchResult} from "../../openaireLibrary/utils/entities/searchResult";

@Component({
    selector: 'openaire-search-dataproviders',
    template: `
      
    <new-search-page
      pageTitle="Search Content Providers"
      entityType="dataprovider"
      type=" Content provider"
      [results]="results"
      [searchUtils]="searchUtils"
      [sortedByChanged]="searchUtils.sortBy"
      [fieldIds]="fieldIds" [fieldIdsMap]="fieldIdsMap" [selectedFields]="selectedFields"
      [simpleSearchLink]="properties.searchLinkToDataProviders"
      [disableForms]="disableForms"
      [disableRefineForms]="disableRefineForms"
      [loadPaging]="loadPaging"
      [oldTotalResults]="oldTotalResults"
      [openaireLink]="'https://' + (properties.environment == 'production'?'':'beta.') + 'explore.openaire.eu/search/find/dataproviders'"
      [includeOnlyResultsAndFilter]="false"
      [hasPrefix]="false"
      searchFormClass="datasourcesTableSearchForm" [entitiesSelection]="false" [showSwitchSearchLink]="false"
      [filters]="filters"
      [simpleView]="true" formPlaceholderText="Search by name..."
      [showResultCount]="false" [showIndexInfo]="false" [showDownload]="false"
      [sort]="false" [showBreadcrumb]="true"
      [customFilter]=customFilter [searchForm]="{dark: false, class: 'search-form'}">
    </new-search-page>

    `

})
export class OpenaireSearchDataprovidersComponent {
  private errorCodes: ErrorCodes;
  private errorMessages: ErrorMessagesComponent;
  public columnNames = ['Name', 'Official Name'];
  public results =[];
  public filters =[];
  public searchUtils:SearchUtilsClass = new SearchUtilsClass();
  public searchFields:SearchFields = new SearchFields();
  public refineFields: string[] = [];// =  this.searchFields.JOURNAL_FIELDS;
  properties:EnvProperties= properties;

  public disableForms: boolean = false;
  public enableSearchView: boolean = true;

  private communityId: string = '';
  subscriptions = [];
  customFilter: SearchCustomFilter = null;
  initialLoad = true;
  public allResults =[];
  @ViewChild(NewSearchPageComponent, { static: true }) searchPage: NewSearchPageComponent;
  public fieldIds:  string[] = this.searchFields.DATASOURCE_ADVANCED_FIELDS;
  public fieldIdsMap= this.searchFields.DATASOURCE_FIELDS;
  public selectedFields:AdvancedField[] =  [];
  public disableRefineForms: boolean = false;
  public loadPaging: boolean = true;
  public oldTotalResults: number = 0;
  keyword;
  constructor (private route: ActivatedRoute, private _searchDataprovidersService: SearchCommunityDataprovidersService, private _communitiesService: CommunitiesService, private _communityService: CommunityService) {
    this.errorCodes = new ErrorCodes();
    this.errorMessages = new ErrorMessagesComponent();
    this.searchUtils.status = this.errorCodes.LOADING;

  }

  public ngOnInit() {
    this.searchUtils.baseUrl = this.properties.searchLinkToDataProviders;
      this.subscriptions.push(this._communityService.getCommunityAsObservable().subscribe(community =>{
        if(community != null) {
          this.communityId = community.communityId;
          this.customFilter = new SearchCustomFilter("Community", "communityId", this.communityId, community.shortTitle);
          this.subscriptions.push(this.route.queryParams.subscribe(params => {
            let page = (params['page'] === undefined) ? 1 : +params['page'];
            this.searchUtils.page = (page <= 0) ? 1 : page;
            this.searchUtils.validateSize(params['size']);
            this.keyword = decodeURIComponent(params['fv0']?params['fv0']:(params['keyword']?params['keyword']:''));
            this.selectedFields = [];
            this.searchPage.prepareSearchPage(this.fieldIds, this.selectedFields, [], [], this.fieldIdsMap, this.customFilter, params, "dataprovider");
            if (this.initialLoad) {
              this.initialLoad = false;
              this._getResults();
            } else {
              this.filterResults();
            }
          }));
        }
    }));

  }

  public ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
    private _getResults(){
      this.searchUtils.status = this.errorCodes.LOADING;
      this.disableForms = true;
      this.enableSearchView = false;
      this.results = [];
      this.searchUtils.totalResults = 0;
      this.subscriptions.push(this._searchDataprovidersService.searchDataproviders(this.properties, this.communityId).subscribe(
          data => {
            this.allResults = this.parseResults(data);
            this.searchUtils.status = this.errorCodes.DONE;
            this.filterResults();
          },
          err => {
            /*
            console.log(err);
             //TODO check erros (service not available, bad request)

            if(err.status == '404') {
              this.searchUtils.status = this.errorCodes.NOT_FOUND;
            } else if(err.status == '500') {
              this.searchUtils.status = this.errorCodes.ERROR;
            } else {
              this.searchUtils.status = this.errorCodes.NOT_AVAILABLE;
            }
            */
            this.handleError("Error getting content providers for community with id: "+this.communityId, err);
            this.searchUtils.status = this.errorMessages.getErrorCode(err.status);

            this.enableSearchView = true;
          }
      ));
    }
  parseResults(data){
    let results:SearchResult[]=[];
    for(let result of data){
      let sResult:SearchResult = new SearchResult();
      sResult.id = result.openaireId;
      sResult.title = {name:"", accessMode: null};
      sResult.title.name = result.officialname?result.officialname:result.name;
      results.push(sResult);
    }
    return results;
  }
  filterResults(){
    let results = this.allResults.filter(value => {return value.title.name && value.title.name.toLowerCase().indexOf(this.keyword.toLowerCase()) !=-1 });
    // this.oldTotalResults = results.length;
    this.searchUtils.totalResults = results.length;
    this.results = results.slice((this.searchUtils.page - 1) * this.searchUtils.size, this.searchUtils.page *this.searchUtils.size );
    this.searchUtils.status = this.results.length == 0 ? this.errorCodes.NONE:  this.errorCodes.DONE;
    this.searchPage.buildPageURLParameters(this.filters, [], false);
    this.disableForms = false;
    this.enableSearchView = true;
  }
  private handleError(message: string, error) {
    console.error("Content Providers simple Search Page: "+message, error);
  }
}
