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 { HostUrlService } from '../../host-url.service';
import { ItemDetail } from '../../ecm-model/product-detail-model';

@Injectable()
export class EcmCheckoutService {
    constructor (private http: Http,public hostUrlService : HostUrlService ) {}
    
    singleItem: ItemDetail;
    
    sendData(data, _tokenid: string): Observable<any> {
        console.log( "inside send data" + JSON.stringify(data));  
        let authUrl = '/ecm/service/order';  // URL to web service
        let _urlParams = new URLSearchParams();
        _urlParams.append('tokenid', _tokenid);
         console.log( "sendLogin 1...." + _urlParams.toString() ); 
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        authUrl = this.hostUrlService.hostUrl + authUrl + '?' + _urlParams.toString();
        console.log( "sendLogin 2...." + authUrl); 
        return this.http.post( authUrl, JSON.stringify(data) , options)
          .map( (res) => this.extractData(res) );
    }
    
    setItem(item){
        this.singleItem = item;
        console.log("the item of set now start",this.singleItem)
    }
    
    getItem(){
        console.log("the item of get now start",this.singleItem)
        return this.singleItem;
    }
    
    reset(){
        this.singleItem = undefined;
    }
    
    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);
    }
}
