import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {map} from "rxjs/operators";
import {ResultLandingInfo} from "../utils/entities/resultLandingInfo";
import {CustomOptions} from "../services/servicesUtils/customOptions.class";
import {WorkV3_0} from "./orcidWork";
import {properties} from "../../../environments/environment";
import {ConnectHelper} from "../connect/connectHelper";

@Injectable()
export class OrcidService {
  constructor(private http: HttpClient) {}

  getPutCode(pids: string) {
    let url: string = properties.orcidAPIURL+"local/put-code?pids="+pids;
    return this.http.get<string[]>(url, CustomOptions.registryOptions());
  }

  getPutCodes(pids: string[][]) {
    let url: string = properties.orcidAPIURL+"local/put-codes";
    return this.http.post<string[][]>(url, JSON.stringify(pids), CustomOptions.registryOptions());
  }

  getLocalWorksByPids(pids: string[][]) {
    let url: string = properties.orcidAPIURL+"local/works";
    return this.http.post<string[][]>(url, JSON.stringify(pids), CustomOptions.registryOptions());
  }

  getToken(code: string) {
    // let url: string = "https://sandbox.orcid.org/oauth/token";
    // let clientId: string = "APP-A5M3KTX6NCN67L91";
    // let clientSecret: string = "96b20d71-ae06-4286-bb00-9172536c1ad4";

    // let body: string = "client_id="+clientId+"&client_secret="+clientSecret+"&grant_type=authorization_code&code="+code+"&redirect_uri=http://duffy.di.uoa.gr:4300";
    //let body: string = "client_id="+clientId+"&client_secret="+clientSecret+"&grant_type=authorization_code&code="+code;
    // console.debug(JSON.stringify(body));
    // console.debug(url);
    // return this.http.post(url, JSON.stringify(body));
      //.pipe(catchError(this.handleError));
    // console.debug(code);
    let url: string = properties.orcidAPIURL+"orcid/token/save?code="+code;
    return this.http.get(url, CustomOptions.registryOptions());
  }

  getRecord() {
    let url: string = properties.orcidAPIURL+"orcid/record";
    return this.http.get(url, CustomOptions.registryOptions());
  }

  saveWork(resultLandingInfo: ResultLandingInfo, pids: string) {
    let work = WorkV3_0.resultLandingInfoConvert(resultLandingInfo, null);
    let portalId: string = ConnectHelper.getCommunityFromDomain(properties.domain);
    // if dashboard format changes, check in API the metrics service ("calculateMetrics" method) for orcid KPIs
    let dashboard: string = properties.environment + "_" + properties.dashboard + (portalId? "_" + portalId : "");
    let result = {
      "dashboard": dashboard,
      "pids": pids.split(","),
      "work": work
    };
    let url: string = properties.orcidAPIURL+"orcid/work/save";
    return this.http.post<any>(url, JSON.stringify(result), CustomOptions.registryOptions())
                    // .pipe(map(res => {
                    //   console.debug(res);
                    //   if(!res) {
                    //     return null;
                    //   }
                    //   work['put-code'] = +res;
                    //   return work;
                    // }));
  .pipe(map(res => {
      // console.debug(res);
      if(!res || !res['putCode']) {
        return null;
      }
      work['put-code'] = +res['putCode'];
      work['created-date'] = {};
      work['created-date']['value'] = res['creationDate'];
      work['last-modified-date'] = {};
      work['last-modified-date']['value'] = res['updateDate'];
      return work;
    }));
  }

  // updateWork(resultLandingInfo: ResultLandingInfo, pids: string, putCode: string) {
  //   let work = WorkV3_0.resultLandingInfoConvert(resultLandingInfo, putCode);
  //   let url: string = properties.orcidAPIURL+"orcid/work/update/"+putCode;
  //
  //     let result = {
  //       "pids": pids.split(","),
  //       "work": work
  //     };
  //     console.log(result);
  //   return this.http.post(url, JSON.stringify(work), CustomOptions.registryOptions())
  //                   .pipe(map(res => work));
  // }
  updateWork(resultLandingInfo: ResultLandingInfo, pids: string, putCode: string) {
    let work = WorkV3_0.resultLandingInfoConvert(resultLandingInfo, putCode);
    let result = {
      "pids": pids.split(","),
      "work": work
    };

    let url: string = properties.orcidAPIURL+"orcid/work/update/"+putCode;
    return this.http.post(url, JSON.stringify(result), CustomOptions.registryOptions())
      .pipe(map(res => {
        if(!res || !res['putCode']) {
          return null;
        }
        work['last-modified-date'] = {};
        work['last-modified-date']['value'] = res['updateDate'];
        return work;
      }));
  }

  getOrcidWorks(putCodes: string[]) {
    let url: string = properties.orcidAPIURL + "orcid/works?put_codes="+putCodes.join(",");
    return this.http.get<any>(url, CustomOptions.registryOptions());
  }


  deleteWork(putCode: string) {
    let url: string = properties.orcidAPIURL+"orcid/work/"+putCode+"/delete";
    return this.http.delete(url, CustomOptions.registryOptions());
  }

  deleteWorks(putCodes: string[]) {
    let url: string = properties.orcidAPIURL+"orcid/works/delete";
    return this.http.post<string[]>(url, JSON.stringify(putCodes), CustomOptions.registryOptions());
  }

  getLocalWorks() {
    let url: string = properties.orcidAPIURL+"local/works";
    return this.http.get<any[]>(url, CustomOptions.registryOptions());
  }

  getUserOrcid() {
    let url: string = properties.orcidAPIURL+"local/orcidId";
    return this.http.get(url, CustomOptions.registryOptions()).pipe(map(res => res['value']));
  }

  getPersonalDetails() {
    let url: string = properties.orcidAPIURL+"orcid/personal-details";
    return this.http.get(url, CustomOptions.registryOptions());
  }
}
