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

import {AppState} from '../ecm-store/reducers';
import { AdressAction} from '../ecm-store/actions';
import { Address } from './address-manager/address.model';
import { HostUrlService } from '../host-url.service';


@Injectable()
export class UserAddressService {

//  private userActionUrl = '/ecm/service/feeds/L2D01';
    private userActionUrl = '/ecm/service/feeds';
    public userAddress;
    
  constructor(private http: Http, private store: Store<AppState>, private addressActions: AdressAction,  public hostUrlService : HostUrlService) { }
  
    fetchUserAddress(): Observable<Address[]> {
        console.log( "fetchUserAddress Called" );
          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.userActionUrl + '/' + siteCode + "/addresses", options )
                     .map( (res) => this.extractData(res) )
                     .catch(this.handleError);
      }
    
    
    addNewAddress( userAdress ) {
        console.log( "addNewAddress StoreInAddress Called" );
        console.log(JSON.stringify(userAdress));
        let headers = new Headers( { 'Content-Type': 'application/json' });
        let options = new RequestOptions( { headers: headers });
        let siteCode = localStorage.getItem('SITE_CODE'); 
        
       return this.http.post( this.hostUrlService.hostUrl+this.userActionUrl + '/' + siteCode +'/address', JSON.stringify(userAdress) , options)
            .map( (res) => this.extractData(res) );
    }
    
    updateUserAddress( userAdress ) {
        console.log( "updateUserAddress StoreInAddress Called" );
        console.log(JSON.stringify(userAdress));
        let headers = new Headers( { 'Content-Type': 'application/json' });
        let options = new RequestOptions( { headers: headers });
        let siteCode = localStorage.getItem('SITE_CODE'); 

        return this.http.post( this.hostUrlService.hostUrl+this.userActionUrl + '/' + siteCode +'/address', JSON.stringify(userAdress) , options)
            .map( (res) => this.extractData(res) );
    }
    
    deleteUserAddress( userAdress ) {
        console.log( "deleteCartItem Called" );
        let siteCode = localStorage.getItem('SITE_CODE'); 
    
        return this.http.delete(this.hostUrlService.hostUrl+ this.userActionUrl + '/' + siteCode + '/address/' + userAdress.lineNo, {})
                        .map(res => res.json());
    }
    
    getSuggestions(field, value) {
        console.log('Query:['+field+']['+value+']');
        let suggestionUrl = this.hostUrlService.hostUrl+'/ecm/service/sys/' + field + '/' + value;
      
        let headers = new Headers( { 'Content-Type': 'application/json' });
        let options = new RequestOptions( { headers: headers });
        
        return this.http.get( suggestionUrl, options )
        .map( (res) => this.extractData(res) )
        .catch( this.handleError );
        
    }
    
    private extractData(res: Response) {
        let respJson = res.json();
        console.log('extracData',respJson);
        if(respJson != null)
        {
            for( let key of Object.keys( respJson ) )
            {
                console.log( "getUserAddress Address ==> key: " + key )
                let data = respJson[key];
                
                try 
                {
                    respJson[key] = JSON.parse( data );
                    console.log( "getUserAddress Address try : " + respJson[key] );
                }
                catch(e)
                {
                    console.log( "getUserAddress Address ==> key: " ,data, typeof data === 'object')
                    if(typeof data === 'object')
                        respJson[key] = this.formatObject(data);
                    else
                        respJson[key] = data;
                    console.log( "getUserAddress Address catch : " + respJson[key] );
                }
            }
            console.log('extractData[' + JSON.stringify(respJson) + ']');
        }
        return respJson || { };
     }
    
    formatObject(respJson: any) {
        
        console.log('formatObject',respJson);
        if(respJson != null)
        {
            for( let key of Object.keys( respJson ) )
            {
                console.log( "formatObject Address ==> key: " + key )
                let data = respJson[key];
                try 
                {
                    respJson[key] = JSON.parse( data );
                    console.log( "formatObject Address try : " + respJson[key] );
                }
                catch(e)
                {
                    respJson[key] = data;
                    console.log( "formatObject Address catch : " + respJson[key] );
                }
            }
            console.log('formatObject[' + JSON.stringify(respJson) + ']');
        }
        return respJson || { };
     }
    
    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);
      }
    
    getAddress() {
        console.log("getItems"+this.userAddress);
      return this.userAddress;
    }
    
    setAddress(userAddress) {
     
     this.userAddress = userAddress;
           console.log("setItems"+this.userAddress);
    }
      


}
