import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";



import {SearchResult}     from '../utils/entities/searchResult';
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
import{EnvProperties} from '../utils/properties/env-properties';
import {StringUtils} from '../utils/string-utils.class';
import {map} from "rxjs/operators";
import {ParsingFunctions} from "../landingPages/landing-utils/parsingFunctions.class";
import {properties} from "../../../environments/environment";

@Injectable()
export class SearchOrganizationsService {
  public parsingFunctions: ParsingFunctions = new ParsingFunctions();

    constructor(private http: HttpClient ) {}

    parseResultsForDeposit(data: any): {"name": string, "id": string}[] {
        let results: {"name": string, "id": string}[] = [];

        let length = Array.isArray(data) ? data.length : 1;

        for(let i=0; i<length; i++) {
            let name: string = '';
            let id: string = '';
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:organization'] : data['result']['metadata']['oaf:entity']['oaf:organization'];
            name = resData.legalname;
            if(name == '') {
                name = resData.legalshortname;
            }

            id = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];

            results.push({"name": name, "id": id});
        }
        return results;
    }

    searchOrganizations (params: string, refineParams:string, page: number, size: number, refineFields:string[] , properties:EnvProperties):any {


        let link = properties.searchAPIURLLAst+"organizations";

        let url = link+"?";
        if(params!= null && params != ''  ) {
            url += params;
        }
        if(refineParams!= null && refineParams != ''  ) {
            url += refineParams;
        }
        url += "&page="+(page-1)+"&size="+size + "&format=json";


        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
                    //.map(res => <any> res.json())
                    .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "organization")]));
    }
    advancedSearchOrganizations (params: string, page: number, size: number, properties:EnvProperties, refineParams:string=null,  refineFields:string[] =null, refineQuery:string = null, minRef: boolean = false):any {
    // &type=organizations
      let url = properties.searchAPIURLLAst+"resources2/?format=json";
      var basicQuery = "(reldatasourcecompatibilityid exact driver or reldatasourcecompatibilityid exact driver-openaire2.0 or " +
                "reldatasourcecompatibilityid exact openaire2.0 or reldatasourcecompatibilityid exact openaire3.0 or reldatasourcecompatibilityid exact openaire4.0 or " +
                "reldatasourcecompatibilityid exact openaire-cris_1.1 or " +
                "reldatasourcecompatibilityid exact openaire2.0_data or reldatasourcecompatibilityid exact hostedBy or relproject=*)";

      // url += "&query=";
      if(params!= null && params != ''  ) {
        // url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
        url +="&query=(" + params + ")";
      // }else{
      //   url +=" ( "+basicQuery+ " ) ";
      }
        if(refineParams!= null && refineParams != ''  ) {
            url += refineParams;
        }
        if(refineQuery) {
            url += "&" + refineQuery;
        }
        url += "&fq="+basicQuery;
      url += "&page="+(page-1)+"&size="+size;
      url += minRef ? "&minRef=true" : "";

      // return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
      return this.http.get((properties.useLongCache && size == 0 && !params && (!refineQuery || !refineQuery.includes("fq="))) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
        //.map(res => <any> res.json())

      .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "organization")]));
    }
    parseResults(data: any): SearchResult[] {
        let results: SearchResult[] = [];

        let length = Array.isArray(data) ? data.length : 1;

        for(let i=0; i<length; i++) {
             let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:organization'] : data['result']['metadata']['oaf:entity']['oaf:organization'];

            var result: SearchResult = new SearchResult();

            result['title'] = {"name": '', "accessMode": ''};

            if(resData.legalshortname) {
              result['title'].name = StringUtils.HTMLToString(String(resData.legalshortname));
            }
            if(!result['title'].name || result['title'].name == '') {
                result['title'].name = StringUtils.HTMLToString(String(resData.legalname));
            }

            //result['title'].url = OpenaireProperties.getsearchLinkToOrganization();
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
            if(!result['id'].startsWith("openorgs____::")) {
              let canId = ParsingFunctions.parseRelCanonicalId(Array.isArray(data) ? data[i] : data, "organization");
              if(canId){
                result['id'] = canId;
              }
            }
            if(resData['rels'].hasOwnProperty("rel")) {
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;

                for(let j=0; j<relLength; j++) {
                    let relation = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'][j] : resData['rels']['rel'];

                    if(relation.hasOwnProperty("to")) {
                        if(relation['to'].class && relation['to'].class.toLowerCase() == "isparticipant") {
                            if(result['projects'] == undefined) {
                                result['projects'] = new Array<
                                    { "id": string, "acronym": string, "title": string,
                                      "funderShortname": string, "funderName": string,
                                      "code": string
                                    }>();
                            }

                            let countProjects = result['projects'].length;

                            result['projects'][countProjects] = {
                                "id": "", "acronym": "", "title": "",
                                "funderShortname": "", "funderName": "",
                                "code": ""
                            }

                            if(relation.title != 'unidentified') {
                                result['projects'][countProjects]['id'] =
                                    /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
                                result['projects'][countProjects]['acronym'] = relation.acronym;
                                result['projects'][countProjects]['title'] = relation.title;
                                result['projects'][countProjects]['code'] = relation.code;
                            } else {
                                result['projects'][countProjects]['id'] = "";
                                result['projects'][countProjects]['acronym'] = "";
                                result['projects'][countProjects]['title'] = "";
                                result['projects'][countProjects]['code'] = "";
                            }

                            if(relation.hasOwnProperty("funding")) {
                                let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;

                                for(let z=0; z<fundingLength; z++) {
                                    let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];

                                    if(fundingData.hasOwnProperty("funder")) {
                                        result['projects'][countProjects]['funderShortname'] = fundingData['funder'].shortname;
                                        result['projects'][countProjects]['funderName'] = fundingData['funder'].name;
                                    }
                                }
                            }

                        }
                    }
                }
            }

            if(resData.country.hasOwnProperty("classname")) {
                result.country = resData.country.classname;
            }

            if(resData['pid'] && properties.environment != "production") {
              result.identifiers = this.parsingFunctions.parseIdentifiers(resData['pid']);
            }

          results.push(result);
        }

        return results;
    }

    numOfOrganizations(url: string, properties:EnvProperties ): any {

      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
                  //.map(res => <any> res.json())
                  .pipe(map(res => res['total']));
    }

    numOfEntityOrganizations(id: string, entity: string, properties:EnvProperties ):any {
        // currently not used - if used fix entity comparison below
        var parameters: string = "";
        if(entity == "organization") {
          parameters = "organizations/"+id+"/organizations/count";
        }

        let url = properties.searchAPIURLLAst+parameters+"?format=json";
        return this.numOfOrganizations(url, properties);
    }

    numOfSearchOrganizations(params: string, properties:EnvProperties, refineParams:string=null ):any {
        let url = properties.searchAPIURLLAst+"organizations/count?format=json";
        if(params != "") {
          url += "&q=" + StringUtils.URIEncode(params);
        }
        if(refineParams!= null && refineParams != ''  ) {
            url += refineParams;
        }
        return this.numOfOrganizations(url, properties);
    }

    numOfSearchOrganizations2(params: string, properties:EnvProperties, refineParams:string=null ):any {
        let url = properties.searchAPIURLLAst+"resources2/?format=json&size=0&type=organizations";
        var basicQuery = "(reldatasourcecompatibilityid exact driver or reldatasourcecompatibilityid exact driver-openaire2.0 or " +
          "reldatasourcecompatibilityid exact openaire2.0 or reldatasourcecompatibilityid exact openaire3.0 or reldatasourcecompatibilityid exact openaire4.0 or " +
          "reldatasourcecompatibilityid exact openaire-cris_1.1 or " +
          "reldatasourcecompatibilityid exact openaire2.0_data or reldatasourcecompatibilityid exact hostedBy or relproject=*)";

        // url += "&query=";
        if(params!= null && params != ''  ) {
        //     url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
          url +="&query=( "+params+ " ) ";
          // }else{
        //     url +=" ( "+basicQuery+ " ) ";
        }
        if(refineParams!= null && refineParams != ''  ) {
            url += refineParams;
        }
        url += "&fq="+basicQuery;
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
          .pipe(map(res => res['meta']['total']));
    }
}
