import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { HostUrlService } from '../../host-url.service';

@Injectable()
export class SearchService {
  
  val;
  constructor(private http:Http, public hostUrlService : HostUrlService) { }
  
  setSearch(value){
   console.log('Set Query:['+value+']');
   this.val=value;            
  }
  
  getSearch(){
   console.log('Set Query:['+this.val+']');
   return this.val;
  }
  
  getSuggestions(value) {
      console.log('Query:['+value+']');
      let solrUrl = this.hostUrlService.hostUrl + '/ecm/service/solr/local2do/';
      solrUrl = solrUrl+value+'/json';
      
      let headers = new Headers( { 'Content-Type': 'application/json' });
      let options = new RequestOptions( { headers: headers });
      
      return this.http.get( solrUrl, options )
      .map( this.extractData )
      .catch( this.handleError );
      
  }
  
  private extractData(res: Response) {
      let body = res.json();
      console.log('extractData[' + JSON.stringify(body) + ']');
      return body || { };
    }

    private handleError (error: Response | any) {
      // In a real world app, we might use a remote logging infrastructure
      let errMsg: string;
      if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
      } else {
        errMsg = error.message ? error.message : error.toString();
      }
      console.error('Service handleError:' + errMsg);
      return Observable.throw(errMsg);
    }
}
