import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Store } from '@ngrx/store';

import { Category } from '../../ecm-model/category-model';
import { HostUrlService } from '../../host-url.service';

@Injectable()
export class EcmCategoryService {

 //   private SERVICE_URL = '/ecm/service/L2D01/category';  // URL to web service
    private SERVICE_URL = '/ecm/service';
    constructor (private http: Http,public hostUrlService : HostUrlService) {}

    getCategories(): Observable<Category[]> {
        let headers = new Headers( { 'Content-Type': 'application/json' });
        let options = new RequestOptions( { headers: headers });
        let siteCode = localStorage.getItem('SITE_CODE');
        console.log('inside get category'+this.hostUrlService.hostUrl)
        return this.http.get( this.hostUrlService.hostUrl+this.SERVICE_URL + '/' + siteCode + '/category', options )
            .map( this.extractData )
            .catch( this.handleError );
    }

    getCategory (catCode : string): Observable<Category> {
      
      let siteCode = localStorage.getItem('SITE_CODE');  
      let categoryUrl = this.hostUrlService.hostUrl+this.SERVICE_URL + '/' + siteCode + '/category' + '/' + catCode;  
      let headers = new Headers({ 'Content-Type': 'application/json' });
      let options = new RequestOptions({ headers: headers });

      return this.http.get(categoryUrl, options)
                      .map(this.extractData)
                      .catch(this.handleError);
    }
    
    getSideOptions(): Observable<any> {
        let headers = new Headers( { 'Content-Type': 'application/json' });
        let options = new RequestOptions( { headers: headers });
        let siteCode = localStorage.getItem('SITE_CODE');
        return this.http.get( this.hostUrlService.hostUrl+this.SERVICE_URL + '/' + siteCode + '/category' + '/summary', 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);
    }

}
