import { SWIFTTYPE_KEY } from './constants';
// import * as Rx from 'rx/dist/rx.all';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export class SearchService {

  private subject: BehaviorSubject<any>;

  constructor(
    private $http,
    private $sce
  ) {
    this.subject = new BehaviorSubject(null);
  }

  public get(): BehaviorSubject<any> {
    return this.subject;
  }

  public updateQuery(query: string): void {
    this.getData(query);
  }

  public getData(query: string, page: number = 1): void {
    let fields = [
      'image',
      'title',
      'type',
      'url',
      'body'
    ];
    let url = `https://api.swiftype.com/api/v1/public/engines/search.json?q=${query}&engine_key=${SWIFTTYPE_KEY}&page=${page}`;
    for (let field of fields) {
      url += `&fetch_fields[page][]=${field}`;
    }
    let trustedUrl = this.$sce.trustAsResourceUrl(url);
    this.$http.jsonp(trustedUrl, {
      jsonpCallbackParam: 'callback',
      cache: true
    })
      .then((result) => {
        this.subject.next(result.data);
      });
  }
}
