import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { FormGroupDirective, NgControl, NgForm, NgModel } from '@angular/forms';
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 { CartActions, WishListActions } from '../ecm-store/actions';

import { ECMSigninService } from './ecm-signin.service';

declare var encPwd: any;

@Component( {
    selector: 'ecm-signin',
    templateUrl: './ecm-signin.component.html',
    styleUrls: ['./ecm-signin.component.css'],
    providers: [ECMSigninService]
})
export class EcmSigninComponent implements OnInit {
    
    @Output() closePanel = new EventEmitter();
    timer : any;
    userData : any;
    showPass : boolean = false;
 
    //@ViewChild('signin') signinFrom: NgForm;
    //@ViewChild('password') passwordRef: NgModel;
    _username : string;
    _password : string;
    _npassword: string;
    _confirm_password: string;

    //@ViewChild('verifyForm') verifyForm: NgForm;
    _verifycode : string;
    verifying: boolean = false;
    vCounter: number = 1;  // verifier counter 
    verifyTimeout: number = 30;
    verifyInterval : any; // default upto verifyTimeout seconds 

    _changepassword1 : string;
    _changepassword2 : string;

    statusPending: boolean = false;
    statusErrorMsg: string;

    constructor(public signinService: ECMSigninService, private store: Store<AppState>, private cartAction:CartActions, private wishListAction:WishListActions) { }

    activeForm: any = 'signInForm';
	activeNGForm: NgForm;

    ngOnInit() {
    }

    scrollIntoView(formChildElement){
        console.log('formChildElement' , formChildElement);
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
            formChildElement.scrollIntoView(true);
        }, 500);
    }

    clearTimer() {
    	clearTimeout(this.timer);
    	this.statusErrorMsg = null;
    }

    register() {
        window.open("/ibase/E12Registration/jsp/Registration.jsp");
    }
    
    forgot(signinForm) {

    	this.activeNGForm = signinForm;
		this.statusPending = true;
    
        this.signinService.forgot( this._username ).subscribe(
            result => {
                console.log( 'comp results[' + result.Response.results + ']status[' + result.Response.status + ']' );
                console.log( 'comp result.results.indexOf [' + result.Response.results.indexOf('{') + ']' );
                this.statusPending = false;
                this.statusErrorMsg = null;
                if( result.Response.status == 'Success' )
                {
                	alert(result.Response.results);
                	this.activeForm = 'verifyForm';
                	this.startVerifier();
                }
                else if( result.Response.status == 'error' )
                {
                    this.activeNGForm.resetForm();
                    this.statusErrorMsg = result.Response.results;
                }
            },
            error => {
                let errorMessage = <any>error;
                console.log( 'comp errorMessage[' + errorMessage + ']' );
            }
        );            
    }

    startVerifier(){
    	this.verifying = true;
    	this.verifyInterval = setInterval(() => {
    		if( this.vCounter < this.verifyTimeout ){
    			this.vCounter++;
    		}
    		else{
    			this.verifying = false;
    			clearInterval(this.verifyInterval);
    			this.vCounter = 1;
    		}
        }, 1000);
    }

    verify(verifyForm) {
    	this.activeNGForm = verifyForm;
    	this.statusPending = true;
        
        this.signinService.verify( this._username, this._verifycode ).subscribe(
            result => {
                console.log( 'comp results[' + result.Response.results + ']status[' + result.Response.status + ']' );
                console.log( 'comp result.results.indexOf [' + result.Response.results.indexOf('{') + ']' );
                this.statusPending = false;
                this.statusErrorMsg = null;
                if( result.Response.status == 'Success' )
                {
                	alert(result.Response.results);
                	this.activeForm = 'changePassForm';
                }
                else if( result.Response.status == 'error' )
                {
                    this.activeNGForm.resetForm();
                    this.statusErrorMsg = result.Response.results;
                }
            },
            error => {
                let errorMessage = <any>error;
                console.log( 'comp errorMessage[' + errorMessage + ']' );
            }
        );
    }

//    changePassword(changePassForm) {
//        this.activeNGForm = changePassForm;
//        this.statusPending = true;
//
//        this.signinService.changePassword( this._username, this._npassword ).subscribe(
//            result => {
//                console.log( 'comp results[' + result.Response.results + ']status[' + result.Response.status + ']' );
//                console.log( 'comp result.results.indexOf [' + result.Response.results.indexOf('{') + ']' );
//                this.statusPending = false;
//                this.statusErrorMsg = null;
//                if( result.Response.status == 'success')
//                {
//                     this.activeForm = 'successForm';
//                }
//                else if( result.Response.status == 'error' )
//                {
//                    this.statusErrorMsg = result.Response.results;
//                    this.activeNGForm.resetForm();
//                }
//            },
//            error => {
//                let errorMessage = <any>error;
//                console.log( 'comp errorMessage[' + errorMessage + ']' );
//            }
//        );
//    }
    
    login(signinForm) {
    	this.activeNGForm = signinForm;
        this.statusPending = true;
        console.log( "login [" + this._username + "][" + this._password + "]"); 
        this.convertIntoSHA256();
        console.log( "login [" + this._username + "][" + this._password + "]"); 
        this.sendLogin();
    }

    convertIntoSHA256() {
        let pwdVal = this._password;
        if( pwdVal && pwdVal.length > 0 )
        {
            pwdVal = encPwd( pwdVal );
            console.log( "convertIntoSHA256 [" + pwdVal + "]"); 
            this._password = pwdVal;
        }
    }
    
    sendLogin() {
        
        this.signinService.sendLogin( this._username, this._password ).subscribe(
            result => {
                console.log( 'comp results[' + result.Response.results + ']status[' + result.Response.status + ']' );
                console.log( 'comp result.results.indexOf [' + result.Response.results.indexOf('{') + ']' );
                this.statusPending = false;
                this.statusErrorMsg = null;
                if( result.Response.status == 'success' )
                {
                    if( result.Response.results && result.Response.results.indexOf('{') != -1 )
                    {
                        this.userData = JSON.parse( result.Response.results );
                        this.userData.jti = this._username;
                        this.userData.profileImageLink = "/ibase/resource/images/users/" + this._username + ".png?temp=" + Math.random();
                        
                        //Fetch User Data and Store in cache
                        this.signinService.fetchUserData().subscribe(
                                response => {
                                    console.log('response[' + response + ']');
                                    if(response){
                                        this.store.dispatch(this.cartAction.loadCartItems());
                                        this.store.dispatch(this.wishListAction.loadWishlistItems());
                                    }
                                });
                        
                        console.log( 'comp Object.keys(this.userData) [' + Object.keys(this.userData) + ']' );
                        localStorage.setItem('userInfo', JSON.stringify( this.userData ) );                       
                    }
                    this.closePanel.emit();
                }
                else if( result.Response.status == 'error' )
                {
                    this.statusErrorMsg = result.Response.results;
                    localStorage.removeItem('userInfo');
                    this.activeNGForm.resetForm();
                    //console.log( "passwordRef" + Object.keys( this.passwordRef.control.errors ) + "]"); 
                    //if( this.passwordRef.control ) 
                    {
                    //    this.passwordRef.control.markAsTouched();
                    }
                }
            },
            error => {
                let errorMessage = <any>error;
                console.log( 'comp errorMessage[' + errorMessage + ']' );
            }
        );
    }
    
}
