<commit_before>import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/toPromise';

import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import {Study} from '../models/study';
import {Patient} from '../models/patient';
import {EndpointService} from './endpoint.service';
import {Constraint} from "../models/constraints/constraint";
import {PatientSetPostResponse} from "../models/patient-set-post-response";
import {Aggregate} from "../models/aggregate";
import {ConceptConstraint} from "../models/constraints/concept-constraint";

@Injectable()
export class ResourceService{

  constructor(private http: Http, private endpointService: EndpointService) {
  }

  /**
   * Currently only handles the 'invalid_token' error, other errors are passed on.
   * @param error
   * @returns {any}
   */
  private handleError(error: Response|any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;

      if (err == 'invalid_token') {
        this.endpointService.invalidateToken();
      }

    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg || 'Server error');
  }

  // -------------------------------------- study calls --------------------------------------

  /**
   * Returns the available studies.
   * @returns {Observable<Study[]>}
   */
  getStudies(): Observable<Study[]> {
    let headers = new Headers();
    let endpoint = this.endpointService.getEndpoint();

    if(endpoint) {
      headers.append('Authorization', `Bearer ${endpoint.accessToken}`);
      let url = `${endpoint.getUrl()}/studies`;
      return this.http.get(url, {
        headers: headers
      })
        .map((response:Response) => response.json().studies as Study[])
        .catch(this.handleError.bind(this));
    }
    else {
      console.error('Could not establish endpoint.');
    }

  }

  getTreeNodes(): Observable<object> {
    let headers = new Headers();
    let endpoint = this.endpointService.getEndpoint();

    if(endpoint) {
      headers.append('Authorization', `Bearer ${endpoint.accessToken}`);

      let url = `${endpoint.getUrl()}/tree_nodes`;
      return this.http.get(url, {
        headers: headers
      })
        .map((response:Response) => response.json().tree_nodes)
        .catch(this.handleError.bind(this));
    }
    else {
      console.error('Could not establish endpoint.');
    }
  }


  // -------------------------------------- patient calls --------------------------------------

  /**
   * Given inclusion constraint and exclusion, retrieve the corresponding patient array
   * @param constraint - the constraint of the patient set to be queried
   * @returns {Observable<Patient[]>}
   */
  getPatients(inclusionConstraint: Constraint, exclusionConstraint: Constraint): Observable<Patient[]> {
    let headers = new Headers();
    let endpoint = this.endpointService.getEndpoint();
    headers.append('Authorization', `Bearer ${endpoint.accessToken}`);

    let inclusion = inclusionConstraint.toQueryObject(); console.log('in: ', inclusionConstraint.toQueryObject());
    let exclusion = {};
    exclusion['type'] = 'negation';
    exclusion['arg'] = exclusionConstraint.toQueryObject(); console.log('ex: ', exclusionConstraint.toQueryObject());
    let combination = {};
    combination['type'] = 'and';
    combination['args'] = [inclusion, exclusion];
    let constraintString = JSON.stringify(combination);

    console.log("run patient query with Constraint: " + constraintString);

    let url = `${endpoint.getUrl()}/patients?constraint=${constraintString}`;<commit_msg>remove console.log<commit_after>import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/toPromise';

import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import {Study} from '../models/study';
import {Patient} from '../models/patient';
import {EndpointService} from './endpoint.service';
import {Constraint} from "../models/constraints/constraint";
import {PatientSetPostResponse} from "../models/patient-set-post-response";
import {Aggregate} from "../models/aggregate";
import {ConceptConstraint} from "../models/constraints/concept-constraint";

@Injectable()
export class ResourceService{

  constructor(private http: Http, private endpointService: EndpointService) {
  }

  /**
   * Currently only handles the 'invalid_token' error, other errors are passed on.
   * @param error
   * @returns {any}
   */
  private handleError(error: Response|any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;

      if (err == 'invalid_token') {
        this.endpointService.invalidateToken();
      }

    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg || 'Server error');
  }

  // -------------------------------------- study calls --------------------------------------

  /**
   * Returns the available studies.
   * @returns {Observable<Study[]>}
   */
  getStudies(): Observable<Study[]> {
    let headers = new Headers();
    let endpoint = this.endpointService.getEndpoint();

    if(endpoint) {
      headers.append('Authorization', `Bearer ${endpoint.accessToken}`);
      let url = `${endpoint.getUrl()}/studies`;
      return this.http.get(url, {
        headers: headers
      })
        .map((response:Response) => response.json().studies as Study[])
        .catch(this.handleError.bind(this));
    }
    else {
      console.error('Could not establish endpoint.');
    }

  }

  getTreeNodes(): Observable<object> {
    let headers = new Headers();
    let endpoint = this.endpointService.getEndpoint();

    if(endpoint) {
      headers.append('Authorization', `Bearer ${endpoint.accessToken}`);

      let url = `${endpoint.getUrl()}/tree_nodes`;
      return this.http.get(url, {
        headers: headers
      })
        .map((response:Response) => response.json().tree_nodes)
        .catch(this.handleError.bind(this));
    }
    else {
      console.error('Could not establish endpoint.');
    }
  }


  // -------------------------------------- patient calls --------------------------------------

  /**
   * Given inclusion constraint and exclusion, retrieve the corresponding patient array
   * @param constraint - the constraint of the patient set to be queried
   * @returns {Observable<Patient[]>}
   */
  getPatients(inclusionConstraint: Constraint, exclusionConstraint: Constraint): Observable<Patient[]> {
    let headers = new Headers();
    let endpoint = this.endpointService.getEndpoint();
    headers.append('Authorization', `Bearer ${endpoint.accessToken}`);

    let inclusion = inclusionConstraint.toQueryObject();
    let exclusion = {};
    exclusion['type'] = 'negation';
    exclusion['arg'] = exclusionConstraint.toQueryObject();
    let combination = {};
    combination['type'] = 'and';
    combination['args'] = [inclusion, exclusion];
    let constraintString = JSON.stringify(combination);

    console.log("run patient query with Constraint: " + constraintString);

    let url = `${endpoint.getUrl()}/patients?constraint=${constraintString}`;
{'fraction_non_alphanumeric': 0.1825386514226322, 'fraction_numerical': 0.0, 'mean_word_length': 3.0282574568288854, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4818198', 'n_tokens_mistral': 2109, 'n_tokens_neox': 2068, 'n_words': 490}