import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {OrganizationInfo} from '../../../utils/entities/organizationInfo';
import {EnvProperties} from '../../../utils/properties/env-properties';
import {ParsingFunctions} from '../../landing-utils/parsingFunctions.class';
import {map} from "rxjs/operators";

@Injectable()
export class OrganizationsDeletedByInferenceService {
  constructor(private http: HttpClient) {
    this.parsingFunctions = new ParsingFunctions();
  }

  public parsingFunctions: ParsingFunctions;

  getDeletedByInferenceResults(id: string, size: string, properties: EnvProperties): any {
    let url = properties.searchAPIURLLAst + 'deletedByInferenceOrganizations/' + id + "?format=json&size=" + size;

    return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
      .pipe(map(res => res['results']))
      .pipe(map(res => this.parseDeletedByInferenceResults(res, properties)));
  }

  parseDeletedByInferenceResults(_results: any, properties: EnvProperties): OrganizationInfo[] {
    let results: OrganizationInfo[] = [];
    if (_results) {
      let organization: OrganizationInfo;

      let length = Array.isArray(_results) ? _results.length : 1;
      for (let i = 0; i < length; i++) {
        organization = new OrganizationInfo();

        var _result = Array.isArray(_results) ? _results[i]['result']['metadata']['oaf:entity'] : _results['result']['metadata']['oaf:entity'];
        organization.objIdentifier = Array.isArray(_results) ? _results[i]['result']["header"]["dri:objIdentifier"] :  _results['result']["header"]["dri:objIdentifier"];

        if (_result) {
          if (_result['oaf:organization']) {
            let data = _result['oaf:organization'];

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

            organization.name = data.legalname;


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

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

          }
          results.push(organization);
        }
      }

      return results;
    }
  }
}
