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



import{EnvProperties} from '../../utils/properties/env-properties';

import { ParsingFunctions } from '../landing-utils/parsingFunctions.class';
import {map} from "rxjs/operators";
import {StringUtils} from "../../utils/string-utils.class";

@Injectable()
export class ProjectService {

    constructor(private http: HttpClient ) {
      this.parsingFunctions = new ParsingFunctions();
    }

    public parsingFunctions: ParsingFunctions;
    projectInfo: ProjectInfo;

    getProjectInfo (id: string, properties:EnvProperties):any {

        let url = properties.searchAPIURLLAst + 'projects/'+id+"?format=json";
        let key = url;

        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:project']))
                    .pipe(map(res => [res,
                                 res['fundingtree'],
                                 res['rels']['rel']]))
                    .pipe(map(res => this.parseProjectInfo(res, properties)));

    }

    getProjectInfoByGrantId (grant: string, funder:string, properties:EnvProperties):any {

      let url =properties.searchAPIURLLAst+ 'resources?query=(oaftype exact project)'+
      'and (projectcode_nt exact "'+grant+'" ) and (fundershortname exact '+'"'+funder+ '"'+')'+"&format=json&size=1";


         let key = url;

        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
                    //.map(res => <any> res.json())
                    .pipe(map(res => res['results'][0]))
                    .pipe(map(res => [res['result']['metadata']['oaf:entity']['oaf:project'],res['result']['header']['dri:objIdentifier']]))
                    .pipe(map(res => [res[0],
                                 res[0]['fundingtree'],
                                 res[0]['rels']['rel'],res[1]]))
                    .pipe(map(res => this.parseProjectInfo(res, properties)));

    }
    /*
    get project strtDate and endDate
    */
    getProjectDates (id: string, properties:EnvProperties):any {

        let url = properties.searchAPIURLLAst+'projects/'+id+"?format=json";
        let key = url+'_projectDates';

        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:project']))
                    .pipe(map(res => [res,
                              res['fundingtree'],
                              res['rels']['rel']]))
                    .pipe(map(res => this.parseProjectDates(id,res)))

    }

    getHTMLInfo(id: string, properties:EnvProperties): any {
        let url = properties.searchAPIURLLAst + 'projects/'+id+"?format=json";
        let key = url;

        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:project']))
                    .pipe(map(res => this.parseHTMLInfo(res)));
    }

    private handleError (error: HttpErrorResponse) {
        console.log(error);
        return throwError(error  || 'Server error');
    }

    parseHTMLInfo (data: any):any {
        let htmlInfo: {"title": string, "acronym": string, "callIdentifier": string};

        if(data != null) {
            htmlInfo = {"title": data.title, "acronym": data.acronym, "callIdentifier": data.callidentifier};
        }
        return htmlInfo;
    }

    parseProjectInfo (data: any, properties:EnvProperties):any {
        this.projectInfo = new ProjectInfo();
        this.projectInfo.funding = {funderName: "", funderShortName: "", code: "", callIdentifier: "",
                                    fundingStream: "", budget: "", contribution: "", currency: ""};

        // ['result']['header']['dri:objIdentifier']
        if(data[3] != null) {
          this.projectInfo.id = data[3];
        }

      // ['result']['metadata']['oaf:entity']['oaf:project']['fundingtree']
      if(data[1] != null) {
            let funding: {"funderName": string, "funderShortname": string, "stream": string};
            funding = this.parsingFunctions.parseFundingTrees(data[1]);
            if(funding.funderName) {
              this.projectInfo.funding.funderName = funding.funderName;
            }
            if(funding.funderShortname) {
              this.projectInfo.funding.funderShortName = funding.funderShortname;
            }
            if(funding.stream) {
              this.projectInfo.funding.fundingStream = funding.stream;
            }
      }

      // ['result']['metadata']['oaf:entity']['oaf:project']
      if(data[0] != null) {
        this.projectInfo.acronym = data[0].acronym;
        if(data[0]['title']) {
          this.projectInfo.title = Array.isArray(data[0]['title']) ? StringUtils.HTMLToString(String(data[0].title[0])) : StringUtils.HTMLToString(String(data[0].title));
        } else {
          this.projectInfo.title = "";
        }
        this.projectInfo.funding.code = data[0].code;
        if(data[0].startdate) {
          let date: number = Date.parse(data[0].startdate);
          this.projectInfo.startDate = (date ? date : null);
        }
        if(data[0].enddate) {
          let date: number = Date.parse(data[0].enddate);
          this.projectInfo.endDate = (date ? date : null);
        }
        if(this.projectInfo.endDate || this.projectInfo.startDate) {
          let todayDate = Date.parse(new Date().toString());
          this.projectInfo.currentDate = todayDate;
          if(this.projectInfo.startDate) {
            let startDate = +(this.projectInfo.startDate);
            if (todayDate < startDate) {
              this.projectInfo.status = "Not started";
            }
          }
          if(this.projectInfo.endDate && !this.projectInfo.status) {
            let endDate = +(this.projectInfo.endDate);
            if (todayDate <= endDate) {
              this.projectInfo.status = "On going";
            } else {
              this.projectInfo.status = "Closed";
            }
          }
        }
        if(this.projectInfo.funding) {
          if(this.projectInfo.funding.funderShortName == "EC") {
            this.projectInfo.openAccessMandatePublications = data[0].oamandatepublications;
            // this.projectInfo.specialClause39 = data[0].ecsc39;
            if(data[0].hasOwnProperty("projectoamandatedata")) {
              this.projectInfo.openAccessMandateDatasets = data[0].projectoamandatedata;
            } else if(data[0].hasOwnProperty("ecarticle29_3")) {
              this.projectInfo.openAccessMandateDatasets = data[0].ecarticle29_3;
            }
            this.projectInfo.funding.callIdentifier = data[0].callidentifier;
          }
          this.projectInfo.funding.budget = data[0].totalcost;//"10000";
          this.projectInfo.funding.contribution = data[0].fundedamount;//"200100";
          this.projectInfo.funding.currency = data[0].currency;//"EUR";
        }
        // if(!Array.isArray(data[0]['summary'])) {
        //   this.projectInfo.description = (data[0]['summary']) ? String(data[0]['summary']) : "";
        // } else {
        //   this.projectInfo.description = (data[0]['summary'][0]) ? String(data[0]['summary'][0]) : "";
        // }
        this.projectInfo.description = this.parsingFunctions.parseDescription(data[0] && data[0].summary?data[0].summary:[]);
      }

      // ['result']['metadata']['oaf:entity']['oaf:project']['rels']['rel']
      if(data[2] != null) {
            this.projectInfo.organizations = [];//new Map<string, string>();

            if(!Array.isArray(data[2])) {
              if(data[2].hasOwnProperty("to") && data[2]['to'].class && data[2]['to'].class.toLowerCase() == "hasparticipant") {
                let acronym: string = "";
                let name: string = "";
                let id: string = "";
                if (data[2].hasOwnProperty("legalshortname")) {
                  acronym = data[2].legalshortname;
                }
                if (data[2].hasOwnProperty("legalname")) {
                  name = data[2].legalname;
                }
                if (!acronym && !name) {
                  // acronym is displayed with link and name only in tooltip
                  acronym = "[no title available]";
                }

                if (data[2].hasOwnProperty("to")) {
                  id = data[2]['to'].content;
                }

                this.projectInfo.organizations.push({"acronym": acronym, "name": name, "id": id});
              }
            } else {
                for(let i=0; i<data[2].length; i++) {
                  let acronym: string = "";
                  let name: string = "";
                  let id: string = "";
                    if(data[2][i].hasOwnProperty("to") && data[2][i]['to'].class && data[2][i]['to'].class.toLowerCase() == "hasparticipant") {
                        if(data[2][i].hasOwnProperty("legalshortname")) {
                          acronym = data[2][i].legalshortname;
                        }
                        if(data[2][i].hasOwnProperty("legalname")) {
                          name = data[2][i].legalname;
                        }
                        if(!acronym && !name){
                          acronym = "[no title available]";
                        }

                        if(data[2][i].hasOwnProperty("to")) {
                            id = data[2][i]['to'].content;
                        }

                        this.projectInfo.organizations.push({"acronym": acronym, "name": name, "id": id});
                    }
                }
            }
        }

        if(this.projectInfo.funding && this.projectInfo.funding.funderShortName == "EC") {
            this.projectInfo.url = properties.cordisURL+this.projectInfo.funding.code;
            this.projectInfo.urlInfo = "Detailed project information (CORDIS)";
        }

        if (data[0]?.measure) {
          this.projectInfo.measure = this.parsingFunctions.parseMeasures(data[0].measure);
        }

        return this.projectInfo;

    }

    parseProjectDates (id: string, data: any):any {
        let project = { id: id, startDate: "", endDate: ""};
        if(data[0] != null) {
            project.startDate = data[0].startdate;
            project.endDate = data[0].enddate;
        }
        return project;

    }

}
