import { Injectable, Output, EventEmitter } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders,HttpErrorResponse } from '@angular/common/http';
// import { Observable } from 'rxjs/Observable';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
import { map } from "rxjs/operators"; 
// import 'rxjs/Rx';
import { throwError } from 'rxjs';

@Injectable()
export class AccountActivityService {
                
    @Output() toggle: EventEmitter<any> = new EventEmitter() ;
    
    private activityData = new BehaviorSubject<any>({});
    currentData = this.activityData.asObservable();
    constructor(private http: HttpClient) { }
    private SERVICE_URL = '/ibase/rest/accountActivity?';  // URL to web service
    getUserActivityData (queryParams:string): Observable<any> {
        console.log( "Inside getUserActivityData service queryParams =" + queryParams);
        let activityUrl =this.getHostURL() + this.SERVICE_URL + queryParams; //"?fromDate=10-02-18";  
        let headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        let options = { headers: headers };
        console.log( "getUserActivityData>>>>>" + activityUrl); 
        return this.http.get<any>( activityUrl, options)
            .pipe(map( (res: any) => this.extractData(res) ));
    }

    
    private extractData(res: Response) {
        let body = res.json();
        console.log('extractData[' + JSON.stringify(body) + ']');
        return body || { };
    }

    private handleError (error: HttpErrorResponse | any) {
        let errMsg: string;
        if (error instanceof HttpErrorResponse)
        {
            //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);
        return throwError(errMsg);
    }
    
    setActivityData(activityData: any)
    {
        this.activityData.next(activityData);
    }
    
    public getHostURL(): string {
        // let HOST_URL: string = '';
        let HOST_URL: any = '';
        HOST_URL = localStorage.getItem( 'HOST_URL' );
        if ( !HOST_URL ) HOST_URL = '';
        console.log( 'getHostURL[', HOST_URL, ']' );
        return HOST_URL;
    }
    
    togglePanel(index: any){
        this.toggle.emit(index);
    }
}
