import { Component,AfterViewChecked, ElementRef, ViewChild, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'
import { MdSnackBar } from '@angular/material';
import { MdDialog, MdDialogRef } from '@angular/material';
import { ItemDetail } from '../../ecm-model/product-detail-model';
import { EcmCategoryComponent } from '../ecm-category/ecm-category.component';
import { Observable } from 'rxjs/Observable';
import { ECMHeaderComponent } from '../../ecm-header/ecm-header.component';

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

import { Item } from '../../ecm-model/product-model';
import { EcmCartService } from './ecm-cart.service';
import { ECMCart } from '../../ecm-model/cart-model';

import { Router, ActivatedRoute } from '@angular/router';

@Component( {
    selector: 'ecm-cart',
    templateUrl: './ecm-cart.component.html',
    styleUrls: ['./ecm-cart.component.css']
})
export class EcmCartComponent implements OnInit, AfterViewChecked  {
    cartItemsDetail: ItemDetail[];
    cartCount = 0;
    catCode;
    displayItem = 3;
    totalPrice: number = 0;
    cartItems : Observable<ItemDetail[]>;
    
    disableScrollDown = false
    
    @Input() isMiniCart: boolean = false;
    @Output() closePanel = new EventEmitter();
    @Output() doActivity = new EventEmitter();
    
    @ViewChild('scrollMe') private myScrollContainer: ElementRef;
    @ViewChild('header') header: ECMHeaderComponent;
    
    constructor( private route: ActivatedRoute, public dialog: MdDialog, private router: Router, public cartService: EcmCartService, public snackBar: MdSnackBar, private http: Http, private store: Store<AppState>, private cartAction: CartActions, private wishListAction:WishListActions, public breadcrumbSerivce: Breadcrumbs) { }

    ngOnInit() {
        this.getCartItem();
        this.scrollToBottom();
        
        let breadcrumb = [{label: 'Home', url: '/home'}, {label: 'Cart', url: 'javascript:void(0)'}];
        this.breadcrumbSerivce.breadcrumbs = breadcrumb;
    }
    
    ngAfterViewChecked() {
        this.scrollToBottom();
    } 

    getCartItem() {
        this.cartItems = this.store.select('cartItems');
        
        this.cartItems.subscribe( cartItems => { 
            this.totalPrice = 0;
            cartItems.forEach(
                    item => { 
                        this.totalPrice = this.totalPrice + (parseFloat( item.itemHeader.itemDiscountedRate ) * item.itemQuantity);
                    }
            );
        });
    }

    userActionUrl = '/ecm/service/feeds/cart';

    deleteCartItem( item ) {
        console.log( "deleteCartItem Called" );
        
        this.store.dispatch(this.cartAction.deleteCartItem(item));
        
        this.getCartItem();
        this.openSnackBar('Item Removed from your Cart' );
        
    }

    showTotalCartItems() {
        this.router.navigate( ['/cart'] );
    }


    increment(item : ItemDetail) {
        item.itemQuantity++;
        let cartData = new Item;
        cartData.itemCode = item.itemCode;
        cartData.itemQuantity = item.itemQuantity;

        this.store.dispatch(this.cartAction.updateCart(cartData));
        this.openSnackBar( 'Quantity increased of ' + item.itemHeader.itemShDescr );
    }

    decrement(item : ItemDetail) {
        item.itemQuantity--;
        let cartData = new Item;
        cartData.itemCode = item.itemCode;
        cartData.itemQuantity = item.itemQuantity;
        this.store.dispatch(this.cartAction.updateCart(cartData));
        this.openSnackBar( 'Quantity decreased of ' + item.itemHeader.itemShDescr );
    }

    checkQantity(item) {
        if (item.itemQuantity == 1)
            return true;
        else
            return false;
    }
    
    moveToWishList(item) {
       
        if(this.checkUser() !== 'undefined' && this.checkUser() !== null && this.checkUser() !== 'null')
        {
            this.store.dispatch(this.cartAction.deleteCartItem(item));
            this.store.dispatch(this.wishListAction.addToWishlistSuccess(item));
            this.openSnackBar('Item Added to your Wishlist');
        }
        else
        {
            this.header.userAction();
        }
    }
    
    openSnackBar( message: string ) {
        this.snackBar.open( message, '', {
            duration: 2000,
        });
    }

    confirmDialog( item: any ) {
        this.cartService.setItemCode( item.itemCode );
        let dialogRef = this.dialog.open( ECMConfirmDialog,{
            width:'300px',
            height:'180px',
            disableClose: true
        });
        dialogRef.componentInstance.dialogTitle = "Remove Item from cart?";
        //dialogRef.componentInstance.confirmMsg = "Would you like to remove item from cart?";
        dialogRef.componentInstance.cancelText = "No";
        dialogRef.componentInstance.confirmText = "Yes";
        dialogRef.afterClosed().subscribe( result => {
            if( result == 'true')
            {
                this.deleteCartItem(item);
            }
        });
    }
    viewItem( itemCode ) {
        this.router.navigate( ['/detail', itemCode] );
    }
    
    scrollToBottom(): void {
        try {
            this.myScrollContainer.nativeElement.scrollBottom = this.myScrollContainer.nativeElement.scrollHeight;
        } catch(err) { }                 
    } 
    
    checkUser(){
        var userInfo = localStorage.getItem( 'userInfo' );
        if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' ) 
        {
            return userInfo;
        }
        else 
        {
            return userInfo;
        }
    }
}

@Component( {
    selector: 'ecm-confirm-dialog',
    templateUrl: 'ecm-confirm-dialog.html',
    styleUrls: ['./ecm-cart.component.css'],
    providers: [EcmCartComponent]
})
export class ECMConfirmDialog {
    @Input() dialogTitle : any;
    @Input() confirmMsg : any;
    @Input() cancelText : any;
    @Input() confirmText : any;
    IS_CART: boolean;

    constructor( public dialogRef: MdDialogRef<ECMConfirmDialog>,private route: ActivatedRoute,private router: Router) { }
    ngOnInit() {
        console.log('route--',this.route,this.route.snapshot,this.router);
        
        let openRoutePath = this.router.url;
        
        
        if(openRoutePath == '/cart'){
            this.IS_CART = true;
        }
    } 
}


@Component({
    selector: 'counter',
    templateUrl: './counter.html',
    styleUrls: ['./ecm-cart.component.css']
  })
  export class CounterComponent{
    
    @Input('quantity') quantity: number;
    @Output() increment = new EventEmitter();
    @Output() decrement = new EventEmitter();
}
