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';

@Injectable()
export class ECMSigninService {
    constructor (public hostUrlService : HostUrlService,private http: Http,) {
        }
 
    sendLogin(_username: string, _password: string): Observable<any> {
        
        
        let authUrl = '/ecm/service/sys/auth/login';  // URL to web service
         console.log( "sendLogin 1...." + this.hostUrlService.hostUrl);  
        let _urlParams = new URLSearchParams();
        _urlParams.append('username', _username);
        _urlParams.append('password', _password);
        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.get( authUrl, options )
                        .map(this.extractData)
                        .catch(this.handleError);
    }
    
    sendLogout(_username: string, _tokenid: string): Observable<any> {
        
        let authUrl = '/ecm/service/sys/auth/logout';  // URL to web service
        let _urlParams = new URLSearchParams();
        _urlParams.append('username', _username);
        _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.get( authUrl, options )
                        .map(this.extractData)
                        .catch(this.handleError);
    }
    
    fetchUserData() {
     
//        let userdataUrl = '/ecm/service/feeds/userdata'; // URL to Web Service
        let userdataUrl = '/ecm/service/feeds';
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let siteCode = localStorage.getItem('SITE_CODE');
        let options = new RequestOptions({ headers: headers });
        console.log( "Fetch user data...." + this.hostUrlService.hostUrl+userdataUrl); 
        return this.http.post( this.hostUrlService.hostUrl+userdataUrl+'/'+siteCode+'/userdata', {}, options )
                        .map(this.extractData)
                        .catch(this.handleError);
    }
         
    forgot(_username: string): Observable<any> {
        
        let authUrl = '/ecm/service/sys/auth/forgot';  // URL to web service
        let _urlParams = new URLSearchParams();
        _urlParams.append('username', _username);
        console.log( "forgot 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( "forgot 2...." + authUrl); 
        return this.http.get( authUrl, options )
                        .map(this.extractData)
                        .catch(this.handleError);
    }

    verify(_username: string, _varcode: string): Observable<any> {
        
        let authUrl = '/ecm/service/sys/auth/verify';  // URL to web service
        let _urlParams = new URLSearchParams();
        _urlParams.append('username', _username);
        _urlParams.append('varcode', _varcode);
        console.log( "verify 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( "verify 2...." + authUrl); 
        return this.http.get( authUrl, options )
                        .map(this.extractData)
                        .catch(this.handleError);
    }

    /*Called from SIGNIN OPTION Forgot Password Request to Change Password*/
    changePassword(_username: string, _npassword: string): Observable<any> {
        
        let authUrl = '/ecm/service/sys/auth/changePassword';  // URL to web service
        let _urlParams = new URLSearchParams();
        _urlParams.append('username', _username);
        _urlParams.append('npassword', _npassword);
        console.log( "changePassword 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( "changePassword 2...." + authUrl); 
        return this.http.get( authUrl, options )
                        .map(this.extractData)
                        .catch(this.handleError);
    }

    /*Called from USER OPTION Change Password Request*/
    changeCurrentPassword(_username: string, _npassword: string, _cpassword: string, _tokenid: string): Observable<any> {
        
        let authUrl = '/ecm/service/sys/auth/changePassword';  // URL to web service
        let _urlParams = new URLSearchParams();
        _urlParams.append('username', _username);
        _urlParams.append('npassword', _npassword);
        _urlParams.append('cpassword', _cpassword);    
        _urlParams.append('tokenid', _tokenid);        
        console.log( "changePassword 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( "changePassword 2...." + authUrl); 
        return this.http.get( authUrl, 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);
    }

}
