import { Component, OnInit, HostListener, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { MdSnackBar } from '@angular/material';

import { AppState } from '../../ecm-store/reducers';
import { Store } from '@ngrx/store';
import { ItemActions, CartActions, WishListActions } from '../../ecm-store/actions';

import { Category } from '../../ecm-model/category-model';
import { SubCategory } from '../../ecm-model/subcategory-model';
import { Item } from '../../ecm-model/product-model';
import { ItemDetail } from '../../ecm-model/product-detail-model';
import { ECMHeaderComponent } from '../../ecm-header/ecm-header.component';

import { ScrollService } from '../../scroll.service';
import { Breadcrumbs } from '../../ecm-breadcrumbs/ecm-breadcrumbs.component';

@Component( {
    selector: 'ecm-product',
    templateUrl: './ecm-product.component.html',
    styleUrls: ['./ecm-product.component.css']
})
export class EcmProductComponent implements OnInit {

    position = 0;
    isCatItems = 'false';
    minVal = 500;
    maxVal = 35000;
    show = 0;
    @HostListener( "window:scroll", [] )
    onWindowScroll() {
        this.position = window.pageYOffset;
    }
    @ViewChild('header') header: ECMHeaderComponent;
    cartItems: Observable<ItemDetail[]>;

    Items = 0;
    private items;
    private filterOptions;    
    private extra_param = { "catCode": '', "catShDesc": '', scatDesc: '' };

    private category;
    private subcategory;
    itemDetail: ItemDetail;
    attribVal;
    attribCode;
    
    constructor( private route: ActivatedRoute, private router: Router, private scroll_service: ScrollService, private store: Store<AppState>, private itemAction: ItemActions, private cartAction: CartActions, private wishlistAction: WishListActions, public snackBar: MdSnackBar,  public breadcrumbSerivce: Breadcrumbs) { }
    ngOnInit() {
        window.scrollTo( 0, 0 );
        this.route.params.subscribe( params => {
            //let id: number = +params['id']; // (+) converts string 'id' to a number
            // In a real app: dispatch action to load the details here.
            let scatCode = params['scatCode'];
            console.log( 'ngOnInit scatCode[' + scatCode + ']' );
            console.log( "Viewtype OpenView" );
            window.scrollTo( 0, 0 );
            //this.getSubCategory( viewKey );
            this.fetchStore( 'SubCategory' );
            this.getItems( scatCode );

        });
        this.cartItems = this.store.select('cartItems');
    }

    getItems( scatCode: string ) {
        this.store.select( 'items' ).subscribe(
                items => {
                    this.items = items;
                    if(this.items)
                    {
                        this.show = this.items.length - 1;
                        this.filterOptions = this.items[this.show];
                        console.log("this.items -->",this.items , this.items.length);
                        console.log("this.items.length -->", this.filterOptions);
                    }
                    let itemDetailObj = this.items[0];
                    if(itemDetailObj)
                    {
                        console.log('Items:[',itemDetailObj);
                        let breadcrumb;
                        if( ! itemDetailObj.subCategory)
                        {
                          breadcrumb = [
                                        {
                                          label: 'Home', 
                                          url: '/home'
                                        },
                                        {
                                          label: itemDetailObj.itemCategory.shDescr, 
                                          url: 'javascript:void(0)'
                                        }
                                       ];
                        }    
                        else
                        {
                          breadcrumb = [
                                         {
                                            label: 'Home', 
                                            url: '/home'
                                         },
                                         {
                                            label: itemDetailObj.itemCategory.shDescr, 
                                            url: '/categories/' + itemDetailObj.itemSubCategory.catCode
                                         },
                                         {
                                            label: itemDetailObj.itemSubCategory.shDescr, 
                                            url: 'javascript:void(0)'
                                         }
                                       ];
                        }
                        this.breadcrumbSerivce.breadcrumbs = breadcrumb;
                    }
                }
        );
    }

    storeItem( selectedItem ) {
        //this.store.dispatch( this.itemAction.getItemSuccess( selectedItem ) );
    }

    fetchStore( viewType: string ) {
        if ( viewType == 'Category' ) {
            this.store.select( 'category' )
                .subscribe( category => this.category = category );
        }

        if ( viewType == 'SubCategory' ) {
            this.store.select( 'subcategory' )
                .subscribe( subcategory => this.subcategory = subcategory );
        }
    }

    addToCart( item: ItemDetail ) {
        item.itemQuantity = 1;
        this.store.dispatch( this.cartAction.addToCartSuccess( item ) );
    }

    addToWishlist( item ) {
        if(this.isAuthUser())
        {
            this.store.dispatch( this.wishlistAction.addToWishlistSuccess( item ) );
            this.openSnackBar('Item Added to your Wishlist');
        }
        else
        {
            this.header.userAction();
        }
    }
    
    removeFromWishlist( item ){
        this.store.dispatch( this.wishlistAction.deleteWishlistItemSuccess( item ) );
        this.openSnackBar('Item Deleted from your Wishlist');
    }
    
    onInputChange( event: any ) {
        this.maxVal = event.value;
    }
    
    openSnackBar( message: string ) {
        this.snackBar.open( message, '', {
            duration: 2000,
        });
    }
    
    isInCart(itemCode): boolean {
        var incart;
        
        this.cartItems.subscribe( cartItems => {
            if(cartItems.find(x => x.itemCode === itemCode))
                incart = true;
            else
                incart = false;
        } );
        
        return incart;
    }
    
    goToCart(){
        this.router.navigate(['/cart']);
    }
    
    isAuthUser(){
        var isAuthUser;
        var userInfo = localStorage.getItem( 'userInfo' );
        if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' )
        { 
            isAuthUser = true;
        }
        else
        {
            isAuthUser = false;
        }
        return isAuthUser;
    }

    //"RED", "WHITE", "BLU_WH", "BLUE", "RED_WH", "PEACH", "BLACK", "YELLOW", "BLK_WH", "BROWN"
    getColor( color ) 
    {
        switch ( color ) 
        {
            case 'RED':
                return 'red';
            case 'WHITE':
                return 'white';
            case 'BLUE':
                return 'blue';
            case 'PEACH':
                return 'peach';
            case 'BLACK':
                return 'black';
            case 'YELLOW':
                return 'yellow';
            case 'BROWN':
                return 'brown';
            default:
                return 'black';
        }
    }
}
