import { Component, Input, Output, Inject, OnInit, OnDestroy, ViewEncapsulation, HostListener, ElementRef, ViewChild, trigger, state, animate, transition, style } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import { ActivatedRoute, Router,ActivatedRouteSnapshot,RoutesRecognized } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';
import { AppState } from '../ecm-store/reducers';
import { Item } from '../ecm-model/product-model';
import { RESIZE_EVENT } from '../ecm-store/ecm-resize';
import { EcmPanelComponent } from '../ecm-view/ecm-panel/ecm-panel.component';

import { ScrollService } from '../scroll.service';
import 'rxjs/add/operator/filter';
import { HostUrlService } from '../host-url.service';

//declare var initSearch: any;
declare var disableScroll: any;
declare var enableScroll: any;

@Component({
  selector: 'ecm-header',
  templateUrl: './ecm-header.component.html',
  styleUrls: ['./ecm-header.component.css'],
  encapsulation: ViewEncapsulation.None,
  animations: [
    trigger('l2dLogoTrans', [
       state('false' , style({ opacity: 1, transform : 'scale(1.0) translateY(0) ' })),
       state('true', style({ transform : ' translateY(0) ' })),
       state('fade150', style({ transform : ' translateX(-10px) translateY(0) scale(0.95)' })),
       state('fade200', style({ transform : ' translateX(-50px) translateY(0) scale(0.85)' })),
       state('fade250', style({ transform : ' translateX(-100px) translateY(0) scale(0.75)' })),
       state('fade300', style({ transform : ' translateX(-150px) translateY(0) scale(0.65)' })),
       state('fade350', style({ transform : ' translateX(-250px) translateY(0) scale(0.55)' })),
       state('fade400', style({ transform : ' translateX(-400px) translateY(50px) scale(0.45)' })),
       state('fade450', style({ transform : ' translateX(-450px) translateY(50px) scale(0.40)' })),
       state('fade500', style({ transform : ' translateX(-500px) translateY(50px) scale(0.35)' })),
       state('fade550', style({ transform : ' translateX(-550px) translateY(50px) scale(0.30)' })),
       state('fade600', style({ transform : ' translateX(-600px) translateY(150px) scale(0.25)' })),
       transition('* <=> *', animate('.3s'))
    ]),
    trigger('fixedHeaderShow', [
      state('fade350', style({ opacity: 0.5, display: 'block' })),
      state('fade400', style({ opacity: 0.6, display: 'block' })),
      state('fade450', style({ opacity: 0.7, display: 'block' })),
      state('fade500', style({ opacity: 0.8, display: 'block' })),
      state('fade550', style({ opacity: 0.9, display: 'block' })),
      state('fade600', style({ opacity: 1.0, display: 'block' }))
    ]),
    trigger('fadeState', [
       state('false' , style({ opacity: 1 })),
       state('true', style({ opacity: 0.99 })),
       state('fade150', style({ opacity: 0.90 })),
       state('fade200', style({ opacity: 0.89 })),
       state('fade250', style({ opacity: 0.79 })),
       state('fade300', style({ opacity: 0.69 })),
       state('fade350', style({ opacity: 0.59 })),
       state('fade400', style({ opacity: 0.49 })),
       state('fade450', style({ opacity: 0.39 })),
       state('fade500', style({ opacity: 0.29 })),
       state('fade550', style({ opacity: 0.19 })),
       state('fade600', style({ opacity: 0.09 })),
       transition('* <=> *', animate('.3s'))
    ]),
    trigger('userState', [
       state('false' , style({ opacity: 1, transform : 'scale(1.0) translateY(0%) ' })),
       state('true', style({ transform : ' translateY(0) ' })),
       state('fade150', style({ transform : ' translateX(0) translateY(0) scale(0.95)' })),
       state('fade200', style({ transform : ' translateX(0) translateY(25px) scale(0.75)' })),
       state('fade250', style({ transform : ' translateX(10px) translateY(75px) scale(0.65)' })),
       state('fade300', style({ transform : ' translateX(25px) translateY(125px) scale(0.55)' })),
       state('fade350', style({ transform : ' translateX(35px) translateY(175px) scale(0.50)' })),
       state('fade400', style({ transform : ' translateX(50px) translateY(225px) scale(0.45)' })),
       state('fade450', style({ transform : ' translateX(55px) translateY(275px) scale(0.40)' })),
       state('fade500', style({ transform : ' translateX(60px) translateY(275px) scale(0.35)' })),
       state('fade550', style({ transform : ' translateX(75px) translateY(300px) scale(0.30)' })),
       state('fade600', style({ transform : ' translateX(80px) translateY(325px) scale(0.25)' })),
       transition('* <=> *', animate('.3s'))
    ])
  ]
})

export class ECMHeaderComponent implements OnInit, OnDestroy {
    @Input() siteHeading: any = 'Local2do';
    @Input() isFixedHeader: boolean = false;
    @Input() headerFadeState = 'false';
    @ViewChild( 'userImage' ) userImage: ElementRef; 
    @ViewChild( 'ecmPanel' ) ecmPanel: EcmPanelComponent;

    userToolTipText : string;
    
    selectedOption: string;
    userData: any;
    sideOption: any;
    cartItems: Observable<Item>;
    cartCounter: number;
    profileImageLink : string;
    clientWidth: any;
    hostUrl;
    constructor(public hostUrlService : HostUrlService, @Inject( DOCUMENT ) private document: Document, private route: ActivatedRoute, private router: Router, private scroll_service: ScrollService, private store: Store<AppState>) {
    	this.hostUrl=this.hostUrlService.hostUrl;
     }

    ngOnInit() {
        console.log( 'ECMHeaderComponent onInit hostUrl' , this.hostUrl);
        this.createUserData();
        this.clientWidth = document.documentElement.clientWidth;
        RESIZE_EVENT.subscribe(data => {
            this.clientWidth = data;
        });
        
        this.cartItems = this.store.select('cartItems');
    }

    ngOnDestroy() {
        console.log( 'ECMHeaderComponent onDestroyed' );
    }

    createUserData() {
        var userInfo = localStorage.getItem( 'userInfo' );
        if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' ) 
        {
            this.userData = JSON.parse( userInfo );
            this.profileImageLink = this.userData.profileImageLink;
            this.userToolTipText = "Click here to Manage Account";
        }
        else 
        {
            this.userData = null;
            this.profileImageLink = "";
            this.userToolTipText = "Click here for Login";
        }
        console.log( 'ECMHeaderComponent getUserInfo ::' + userInfo + ' \n this.userData :: ' + this.userData );
    }

    @HostListener( 'window:scroll', ['$event.target'] )
    onWindowScroll() {

        let scrollTop: number = this.document.body.scrollTop;
        if( scrollTop == 0 )
        {
            scrollTop = window.scrollY;
        }

        if ( ! this.isFixedHeader ) {
            if ( scrollTop > 10 && scrollTop < 50 ) {
                this.headerFadeState = 'true';
            } else if ( scrollTop > 50 && scrollTop < 150 ) {
                this.headerFadeState = 'fade150';
            } else if ( scrollTop > 150 && scrollTop < 200 ) {
                this.headerFadeState = 'fade200';
            } else if ( scrollTop > 200 && scrollTop < 250 ) {
                this.headerFadeState = 'fade250';
            } else if ( scrollTop > 250 && scrollTop < 300 ) {
                this.headerFadeState = 'fade300';
            } else if ( scrollTop > 300 && scrollTop < 350 ) {
                this.headerFadeState = 'fade350';
            } else if ( scrollTop > 350 && scrollTop < 400 ) {
                this.headerFadeState = 'fade400';
            } else if ( scrollTop > 400 && scrollTop < 450 ) {
                this.headerFadeState = 'fade450';
            } else if ( scrollTop > 450 && scrollTop < 500 ) {
                this.headerFadeState = 'fade500';
            } else if ( scrollTop > 500 && scrollTop < 550 ) {
                this.headerFadeState = 'fade550';
            } else if ( scrollTop > 550 ) {
                this.headerFadeState = 'fade600';
            } else if ( scrollTop < 10 ) {
                this.headerFadeState = 'false';
            }
        }

        //console.log('headerFadeState[' + this.headerFadeState + ']' + scrollTop + 'window.scrollY['+ window.scrollY+']');
        localStorage.setItem( 'scrollTop', scrollTop + '' );
        //this.scrollTop = scrollTop;
        //localStorage.setItem('scrollHeight', document.body.scrollHeight + '');
    }

    ngAfterViewInit() {
        //Removed Collapsible Search
        //initSearch(); 
    }
    
    userAction() {
        this.createUserData();

        if( this.clientWidth < 640 )
        {
            //show overlay  with user-option
            if ( this.userData )
            {
                this.ecmPanel.open({ type: 'overlay', option: 'USER_OPT', top:'0px', left: '0px', width:'100%', height: '100%' });
            }
            else
            {
                this.ecmPanel.open({ type: 'overlay', option: 'SIGNIN_OPT', top:'0px', left: '0px', width:'100%', height: '100%' });
            }
        }
        else 
        {
            if ( this.userData )
            {
                //show sidepanel with user-option
                this.ecmPanel.open({ type: 'inplace', option: 'USER_OPT', top:'65px', left: '', right: '20px', width:'300px', height: '400px' });
            }
            else
            {
                //show overlay with sign-in-option
                this.ecmPanel.open({ type: 'overlay', option: 'SIGNIN_OPT', top:'100px', left: 'calc( 50% - 375px / 2 )', width:'375px', height: '535px' });
            }
            
        }        
    }

    cartAction() {
        let openRoutePath = this.route.snapshot.url[0].path;
        this.cartItems.subscribe(items => this.cartCounter = items.length);
        
        if(openRoutePath !== 'cart')
        {
            if( this.clientWidth < 640 )
            {
              this.router.navigate(['/cart']);
            }
            else
            {
               //show sidepanel with cart-option
               if(this.cartCounter == 0)
               {
                   this.ecmPanel.open({ type: 'inplace', option: 'CART_OPT', top:'65px', left: '', right: '75px', width:'300px', height: '320px'});
               }
               else
               {
                   this.ecmPanel.open({ type: 'inplace', option: 'CART_OPT', top:'65px', left: '', right: '75px', width:'400px', height: '' });
               }
            }
        }
    }
    
    searchAction() {
        //show overlay(height:60px) with ecm-search
        this.ecmPanel.open({ type: 'overlay', option: 'SEARCH_OPT', hideClose: true, top:'65px', right: '75px', left: '0px', width:'100%', height: '60px' });
    }
    
    menuAction() {
        if( this.clientWidth < 640 ){
            this.ecmPanel.open({ type: 'overlay', option: 'MENU_OPT', top:'', right: '', width:'80%', height: '100%' });
        }
        else {
            this.ecmPanel.open({ type: 'inplace', option: 'MENU_OPT', hideClose: true , top:'60px', left: '16px', width:'280px', height: '75%' });
        }
    }

    updateProfileImages() {
        var userInfo = localStorage.getItem( 'userInfo' );
        if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' ) 
        {
            this.userData = JSON.parse( userInfo );
   	        console.log( 'HEADER CHANGES B4: profileImageLink' + this.profileImageLink);
            this.profileImageLink = this.userData.profileImageLink;
   	        console.log( 'HEADER CHANGES AFTER: profileImageLink' + this.profileImageLink);
        }

        console.log(this.userImage);
        console.log(this.userImage.nativeElement.src);
        console.log(this.userImage.nativeElement.src.indexOf('/ibase/'));
        console.log(this.userImage.nativeElement.src.indexOf('/ecm/'));
    }
    
    closeMenu() {
        console.log('Close------');
        this.ecmPanel.close();
    }
    
}


