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 { SavedCardAction } from '../ecm-store/actions';
import { Card } from './card-manager/card.model';
import { HostUrlService } from '../host-url.service';


@Injectable()
export class UserCardService {

//    private userActionUrl = '/ecm/service/feeds/L2D01/';

    private userActionUrl = '/ecm/service/feeds';
    userCard: Card[];

    constructor(public hostUrlService : HostUrlService, private http: Http, private store: Store<AppState>, private savedcardActions: SavedCardAction ) { }

    loadUserCard() {
        this.fetchUserCards().subscribe(
            data => {
                this.userCard = data;
                if ( data && data != null ) {
                    this.userCard.forEach( userCard => {
                        this.store.dispatch( this.savedcardActions.addNewCard( userCard ) );
                    })
                }
            });
    }

    fetchUserCards(): Observable<Card[]> {

        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 + '/' +'cards', options )
            .map(( res ) => this.extractData( res ) );
    }

    updateUserCard( userCard ) {
        console.log( "StoreInCard Called" );
        console.log( JSON.stringify( userCard ) );
        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 + '/' + 'card/', JSON.stringify( userCard ), options )
            .map(( res ) => this.extractData( res ) );
    }
    
    addUserCard( card ){
        console.log( "AddCardService Called" );
        console.log( JSON.stringify( card ) );
        
        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 + '/' +'card/', JSON.stringify( card ), options )
            .map(( res ) => this.extractData( res ) );
    }

    
    deleteUserCard( card: Card ) {
        console.log( "deleteUserCard Called", card);
        let siteCode = localStorage.getItem('SITE_CODE'); 

        return this.http.delete( this.hostUrlService.hostUrl+this.userActionUrl + '/' + siteCode + '/'  + 'card/' + card.lineNo, {})
            .map( res => res.json() );

    }


    private extractData( res: Response ) {
        let respJson = res.json();
        console.log( 'extracData', respJson );
        if ( respJson != null ) {
            for ( let key of Object.keys( respJson ) ) {
                console.log( "getUserCard Card ==> key: " + key )
                let data = respJson[key];

                try {
                    respJson[key] = JSON.parse( data );
                    console.log( "getUserCard Card try : " + respJson[key] );
                }
                catch ( e ) {
                    console.log( "getUserCard Card ==> key: ", data, typeof data === 'object' )
                    if ( typeof data === 'object' )
                        respJson[key] = this.formatObject( data );
                    else
                        respJson[key] = data;
                    console.log( "getUserCard Card 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 Card ==> key: " + key )
                let data = respJson[key];
                try {
                    respJson[key] = JSON.parse( data );
                    console.log( "formatObject Card try : " + respJson[key] );
                }
                catch ( e ) {
                    respJson[key] = data;
                    console.log( "formatObject Card 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 );
    }



}
