import { Component, OnInit, Input, Output, EventEmitter, ViewEncapsulation, ViewChild } from '@angular/core';
import { ECMSigninService } from '../ecm-signin/ecm-signin.service';
import { EcmCartService } from '../ecm-view/ecm-cart/ecm-cart.service';
import { EcmLocationService } from '../ecm-search/ecm-location.service';
import { FormGroupDirective, NgControl, NgForm, NgModel } from '@angular/forms';
import { ActivatedRoute, Router,ActivatedRouteSnapshot,RoutesRecognized } from '@angular/router';

import { Store } from '@ngrx/store';
import { AppState } from '../ecm-store/reducers';
import { CartActions } from '../ecm-store/actions';
import { Observable } from 'rxjs/Observable';
import { EcmLocation } from '../ecm-search/ecm-location';
import { HostUrlService } from '../host-url.service';

declare var getContentPlugin: any;

@Component({
  selector: 'ecm-user-option',
  templateUrl: './ecm-user-option.component.html',
  styleUrls: ['./ecm-user-option.component.css'],
  providers: [ECMSigninService],
  encapsulation: ViewEncapsulation.None
})
export class EcmUserOptionComponent implements OnInit {

    @Output() closePanel = new EventEmitter();
    @Output() updateProfileImages = new EventEmitter();
    
    public storeUserLocation :  Observable<EcmLocation>;
    public userLocation : EcmLocation;

    selectedOption: string;
    contentPluginViewUI: any;
    userData: any;
    @Input('activeScreen') activeScreen : string = 'userInfoScreen';
    @Input('fullProfile') fullProfile : boolean = false;
    
    _current_password: string;
    _new_password: string;
    _confirm_password: string;
    timer : any;
    hostUrl;
    constructor(public hostUrlService : HostUrlService, public signinService: ECMSigninService, private store: Store<AppState>, public cartService: EcmCartService, private cartAction: CartActions, private locationService: EcmLocationService, private route: ActivatedRoute, private router: Router) {
         this.hostUrl=this.hostUrlService.hostUrl;
     }

    ngOnInit() {
        console.log( 'ECMUserOption onInit hostUrl' , this.hostUrl);
        var userInfo = localStorage.getItem( 'userInfo' );
        console.log( 'EcmUserOptionComponent getUserInfo ::' + userInfo );
        if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' ) {
            this.userData = JSON.parse( userInfo );
            
            this.storeUserLocation = this.store.select('location');
            this.storeUserLocation.subscribe( userLocation => {
                  //console.log( 'ngOnInit >' + userLocation );
                  this.userLocation = userLocation;
            });
            
            //this.profileImageLink = "/ibase/resource/images/users/" + this.userData.jti + ".png";
        }
    }
    
    openDialog( userid: string, isprofileimage: string ) {

        var userInfo = localStorage.getItem( 'userInfo' );
        console.log( 'EcmUserOptionComponent getUserInfo ::' + userInfo );
        if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' ) {
            this.userData = JSON.parse( userInfo );
        }

        console.log( "loadImage check window.getContentsPlugin " );
        if ( !getContentPlugin ) {
            console.log( "window.getContentPlugin is null" );
            return;
        }
        // Get the target element in which you want to add ContentPlugin.
        console.log( "loadImage after check window.getContentPlugin " );

        this.contentPluginViewUI = getContentPlugin( {
            USER_ID: this.userData.jti,
            IS_PROFILE_IMAGE: true || false,
            HOST_URL: "",
            IS_HOSTED_MODE: true || false,
        }, this, 'changeProfileImages');

        console.log( "USER _ID " + this.userData.jti );

        let targetDiv = document.getElementById( 'targetContent' );
        console.log( targetDiv );
        if ( targetDiv && this.contentPluginViewUI ) {
            targetDiv.innerHTML = "";
            targetDiv.appendChild( this.contentPluginViewUI );
        }

    }

    changeProfileImages = function() {
        console.log( 'USER OPTION : changeProfileImages' );
        //this.profileImageLink = "/ibase/resource/images/users/" + this.userData.jti + ".png?temp=" + Math.random();
        this.userData.profileImageLink = "/ibase/resource/images/users/" + this.userData.jti + ".png?temp=" + Math.random();
        console.log( 'USER OPTION : changeProfileImages' + JSON.stringify( this.userData ));
        localStorage.setItem( 'userInfo', JSON.stringify( this.userData ) );
        this.updateProfileImages.emit();
    }
    
    logout() {

        localStorage.removeItem( 'userInfo' );
        this.store.dispatch(this.cartAction.resetCart());
        
        this.signinService.sendLogout( this.userData.jti, this.userData.TOKEN_ID ).subscribe(
            result => {
                console.log( 'comp result.results.indexOf [' + result.Response.results.indexOf( '{' ) + ']' );
                if ( result.Response.status == 'success' ) {
                    console.log( 'Logging Out' );
                    
                    this.userData = null;
                    localStorage.removeItem( 'userInfo' );
                    this.store.dispatch(this.cartAction.resetCart());
                    this.store.dispatch(this.cartAction.loadCartItems());
                }
                else if ( result.Response.status == 'error' ) {
                    this.userData = null;
                    
                    this.store.dispatch(this.cartAction.resetCart());
                    this.store.dispatch(this.cartAction.loadCartItems());
                }
                
                let openRoutePath = this.route.snapshot.url[0].path;
                if(openRoutePath !== 'home')
                {
                    this.router.navigate(['/home']);
                }
            },
            error => {
                let errorMessage = <any>error;
                console.log( 'comp errorMessage[' + errorMessage + ']' );
            }
        );
        
    }
    
    updateLocation() {
        this.locationService.getGeoLocation();
    }

    changePassword(chgForm: NgForm) {
                
        this.signinService.changeCurrentPassword( this.userData.jti, this._new_password, this._current_password, this.userData.TOKEN_ID ).subscribe(
                result => {
                    console.log( 'comp result.results.indexOf [' + result.Response.results.indexOf( '{' ) + ']' );
                    if ( result.Response.status == 'success' ) {
                        console.log( 'Logging Out' );
                        alert(result.Response.results);
                        this.activeScreen = 'successForm';
                        this.userData = null;
                        //TODO Load Login Screen
                        this.closePanel.emit();
                    }
                    else if ( result.Response.status == 'error' ) {
                        chgForm.resetForm();
                    }
                },
                error => {
                    let errorMessage = <any>error;
                    console.log( 'comp errorMessage[' + errorMessage + ']' );
                }
          );
    }
    
    scrollIntoView(formChildElement){
        console.log('formChildElement' , formChildElement);
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
            formChildElement.scrollIntoView(true);
        }, 500);
    }
}
