import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {throwError} from 'rxjs';
import {OrganizationInfo} from '../utils/entities/organizationInfo';



import{EnvProperties} from '../utils/properties/env-properties';
import {map} from "rxjs/operators";
import {ParsingFunctions} from "../landingPages/landing-utils/parsingFunctions.class";
import {properties} from "../../../environments/environment";

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

    constructor(private http: HttpClient ) {}

    organizationInfo: OrganizationInfo;

    getOrganizationInfo (id: string, properties:EnvProperties):any {
         let url = properties.searchAPIURLLAst+'organizations/'+id+'?format=json';
           //'&query=( (oaftype exact organization) and (reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or reldatasourcecompatibilityid=openaire4.0 or reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy or relprojectid=*  or reldatasourcecompatibilityid = native)) and ( objIdentifier ='+id+')';

        return this.http.get((properties.useCache)? (properties.cacheUrl +encodeURIComponent(url)): url)
                    //.map(res => <any> res.json())
                    //.pipe(map(res => res['results']))
                    //.pipe(map(res => res['result']['metadata']['oaf:entity']['oaf:organization']))
                    //.map(res => [res, res['rels']['rel']])
                    .pipe(map(res => this.parseOrganizationInfo(res)));


    }

    getOrganizationNameAndUrlById(id: string, properties: EnvProperties): any {
      let url = properties.searchAPIURLLAst+"organizations/"+id+"?format=json";

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

    private handleError (error: HttpErrorResponse) {
    // in a real world app, we may send the error to some remote logging infrastructure
    // instead of just logging it to the console
        console.log(error);
        return throwError(error  || 'Server error');
    }

    parseOrganizationInfo (data: any):any {
        this.organizationInfo = new OrganizationInfo();
        this.organizationInfo.relcanId = ParsingFunctions.parseRelCanonicalId(data,"organization");
        let organization;
        let relations;
        if(data != null) {
            organization = data['result']['metadata']['oaf:entity']['oaf:organization'];
            this.organizationInfo.objIdentifier = data["result"]["header"]["dri:objIdentifier"];
            if(this.organizationInfo.objIdentifier.startsWith("openorgs____::")) {
              this.organizationInfo.relcanId = this.organizationInfo.objIdentifier;
            }
            relations = data['result']['metadata']['oaf:entity']['oaf:organization']['rels']['rel'];
        } else {
            return null;
        }

        if(organization != null) {

            if(organization.hasOwnProperty("websiteurl")) {
                this.organizationInfo.title = {"name": organization.legalshortname, "url": organization.websiteurl};
            } else {
                this.organizationInfo.title = {"name": organization.legalshortname, "url": ''};
            }

            this.organizationInfo.name = organization.legalname;

            if(!this.organizationInfo.title.name || this.organizationInfo.title.name == '') {
                this.organizationInfo.title.name = this.organizationInfo.name;
            }

            if(organization.hasOwnProperty("country")) {
                this.organizationInfo.country = organization['country'].classname;
            }

            if (organization.hasOwnProperty("children")) {
              let children = organization['children'];
              if( children.hasOwnProperty("organization")) {
                this.organizationInfo.deletedByInferenceIds = [];
                let length = Array.isArray(children['organization']) ? children['organization'].length : 1;

                for (let i = 0; i < length; i++) {
                  let result = Array.isArray(children['organization']) ? children['organization'][i] : children['organization'];
                  this.organizationInfo.deletedByInferenceIds.push(result.objidentifier);
                }
              }
            }

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

//Comment Parsing Projects info
/*
        if(data[1] != null) {

            let counter;
            let length = relations.length!=undefined ? relations.length : 1;

            for(let i=0; i<length; i++) {
                let relation = relations.length!=undefined ? relations[i] : relations;
                if(relation.hasOwnProperty("to")) {
                    if(relation['to'].class == "isParticipant") {
                        if(relation.hasOwnProperty("funding")) {
                            if(relation['funding'].hasOwnProperty("funder")) {
                                if(this.organizationInfo.projects == undefined) {
                                    this.organizationInfo.projects = new Map<string,
                                        { "name": string, "id": string, "code": string,
                                          "acronym": string, "funder": string, "funderId": string,
                                          "fundingStream": string, "fundingLevel1": string, "fundingLevel2": string,
                                          "sc39": string, "startDate": string, "endDate": string }[]>();
                                }

                                if(!this.organizationInfo.projects.has(relation['funding']['funder'].name)) {
                                    this.organizationInfo.projects.setValues(relation['funding']['funder'].name,
                                        new Array<{ "name": string, "id": string, "code": string,
                                                    "acronym": string, "funder": string, "funderId": string,
                                                    "fundingStream": string, "fundingLevel1": string, "fundingLevel2": string,
                                                    "sc39": string, "startDate": string, "endDate": string }>());
                                }

                                counter = this.organizationInfo.projects.get(relation['funding']['funder'].name).length;
                                this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter] =
                                    { "name": "", "id": "", "code": "",
                                      "acronym": "", "funder": "", "funderId": "",
                                      "fundingStream": "", "fundingLevel1": "", "fundingLevel2": "",
                                      "sc39": "", "startDate": "", "endDate": "" };

                                //let url = "";
                                if(relation['to'].content != null && relation['to'].content != "") {
                                    this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['id'] = relation['to'].content;
                                    //url = OpenaireProperties.getsearchLinkToProject()+relation['to'].content;
                                }
                                this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['name'] = relation.title;
                                //this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['url'] = url;
                                this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['code'] = relation.code;
                                this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['acronym'] = relation.acronym;

                                this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['funder'] = relation['funding']['funder'].shortname;
                                this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['funderId'] = relation['funding']['funder'].id;
                                if(relation['funding'].hasOwnProperty("funding_level_0")) {
                                    this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['fundingStream'] = relation['funding']['funding_level_0'].name;
                                }
                                if(relation['funding'].hasOwnProperty("funding_level_1")) {
                                    this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['fundingLevel1'] = relation['funding']['funding_level_1'].name;
                                }
                                if(relation['funding'].hasOwnProperty("funding_level_2")) {
                                    this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['fundingLevel2'] = relation['funding']['funding_level_2'].name;
                                }
                                //this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['sc39'] =
                                //this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['startDate'] =
                                //this.organizationInfo.projects.get(relation['funding']['funder'].name)[counter]['endDate'] =
                            }
                        }

                    }


                    } /*else if(relation['to'].class == "isProvidedBy") {

                        if(this.organizationInfo.dataProviders == undefined) {
                            this.organizationInfo.dataProviders = new Array<{ "name": string, "url": string, "type": string, "websiteUrl": string , "organizations": {"name": string, "url": string}[]}>();
                        }

                        counter = this.organizationInfo.dataProviders.length;
                        this.organizationInfo.dataProviders[counter] = { "name": "", "url": "", "type": "", "websiteUrl": "", "organizations": [] }

                        let url="";
                        if(relation['to'].content != null && relation['to'].content != "") {
                            url = OpenaireProperties.getsearchLinkToDataProvider()+relation['to'].content;
                        }
                        this.organizationInfo.dataProviders[counter]['name'] = relation.officialname;
                        this.organizationInfo.dataProviders[counter]['url'] = url;
                        if(relation.hasOwnProperty("datasourcetype")) {
                            this.organizationInfo.dataProviders[counter]['type'] = relation['datasourcetype'].classname;
                        }
                        this.organizationInfo.dataProviders[counter]['websiteUrl'] = relation.websiteurl;
                    }*/
/* ----->
                }
            }
        }
*/
        return this.organizationInfo;

    }

    parseOrganizationNameAndUrl(organization: any): any {
      let title: {"name": string, "url": string} = {"name": "", "url": ""};

      if(organization != null) {
        if(organization.hasOwnProperty("websiteurl")) {
            title = {"name": organization.legalshortname, "url": organization.websiteurl};
        } else {
            title = {"name": organization.legalshortname, "url": ''};
        }

        if(title.name == '') {
            title.name = organization.legalname;
        }
      }

      return title;
    }

}
