import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MdSnackBar } from '@angular/material';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { RESIZE_EVENT } from '../ecm-store/ecm-resize';

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

import { EcmProductDetailService } from './ecm-product-detail.service';
import { ScrollService } from '../scroll.service';
import { EcmProductReviewService } from './ecm-product-review.service';

import { ItemDetail } from '../ecm-model/product-detail-model';
import { EcmTemplateItem,EcmTemplateComponent } from './ecm-template/ecm-template.component';
import { EcmOutingComponent } from './ecm-template/ecm-outing.component';
import { EcmFoodComponent } from './ecm-template/ecm-food.component';
import { EcmCelebrationComponent } from './ecm-template/ecm-celebration.component';
import { EcmHandicraftComponent } from './ecm-template/ecm-handicraft.component';
import { EcmTrainingComponent } from './ecm-template/ecm-training.component';
import { EcmGeneralComponent } from './ecm-template/ecm-general.component';
import { EcmProductReviewComponent } from './ecm-product-review.component';
import { EcmRelatedItemsComponent } from '../ecm-view/ecm-related-items/ecm-related-items.component';
import { ECMCart } from '../ecm-model/cart-model';
import { Item } from '../ecm-model/product-model';
import { ECMHeaderComponent } from '../ecm-header/ecm-header.component';
import { Reviews } from '../ecm-model/product-review.model';
import { MdDialog, MdDialogRef, MdDialogConfig, MD_DIALOG_DATA } from '@angular/material';
import { EcmPanelComponent } from '../ecm-view/ecm-panel/ecm-panel.component';
import { Breadcrumbs } from '../ecm-breadcrumbs/ecm-breadcrumbs.component';

import { EcmCheckoutService } from '../ecm-view/ecm-checkout/ecm-checkout.service';

export const ECM_TEMPLATES: any = {
                                   'ecm-outing' : new EcmTemplateItem(EcmOutingComponent), 
                                   'ecm-food' : new EcmTemplateItem(EcmFoodComponent),
                                   'ecm-celebration' : new EcmTemplateItem(EcmCelebrationComponent),
                                   'ecm-handicraft' : new EcmTemplateItem(EcmHandicraftComponent),
                                   'ecm-training' : new EcmTemplateItem(EcmTrainingComponent),
                                   'ecm-general' : new EcmTemplateItem(EcmGeneralComponent)
                                  };

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

  @ViewChild('reviewsAndRating') reviewsAndRating: ElementRef;
  @ViewChild('header') header: ECMHeaderComponent;
  @ViewChild( 'ecmPanel' ) ecmPanel: EcmPanelComponent;
  clientWidth: any;
  
  itemCode: string;
  ecmTemplate: EcmTemplateItem;
  itemDetail;
  scatCode;
  noOfReviews;
  userReview: Reviews;
  attribVal;
  attribCode;
  
  constructor(private route: ActivatedRoute, private router:Router, public productDetailService: EcmProductDetailService, public snackBar: MdSnackBar, private store: Store<AppState>,  private productreviewService: EcmProductReviewService, public dialog: MdDialog, private cartActions: CartActions, private itemAction:ItemActions, private wishListAction:WishListActions, public breadcrumbSerivce: Breadcrumbs, public checkOutService: EcmCheckoutService) { }

  ngOnInit() {
        this.clientWidth = document.documentElement.clientWidth;
          RESIZE_EVENT.subscribe(data => {
              this.clientWidth = data;
        });
      
	    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.
          this.itemCode = params['itemCode'];
           console.log( 'ngOnInit itemCode[' + this.itemCode + ']' );
           window.scrollTo(0,0);
           //this.getItemFromStore();
           
           this.store.dispatch( this.itemAction.getItem(this.itemCode) );
           
           this.getItemDetail(this.itemCode);
       });
  }
  
  getItemFromStore(){
      let items: Observable<Item[]> = this.store.select('items');
      let item;
  
      items.subscribe( items => {
          item = items.find(x => x.itemCode === this.itemCode);
          this.store.dispatch( this.itemAction.getItemSuccess(item) );     
      });
  }
  
  getItemDetail( itemCode: string ) {
      
      this.store.select('item')
          .subscribe( itemDetail => { 
           this.itemDetail = itemDetail 
           console.log('Item Detail ****',itemDetail);
           if ( this.itemDetail.itemCategory ) {
               this.storeCatSubcat();
               let ecmTemplateName = this.itemDetail.itemCategory.ecmTemplate;
               console.log( "getItemDetail ecmTemplateName: " + ecmTemplateName )
               if(ecmTemplateName==null)
               {
                   this.ecmTemplate = ECM_TEMPLATES['ecm-general'];
                   console.log( "Sorry, the " + ecmTemplateName + " is not in the system yet!" );
                   console.log('--ecmTemplate---',this.ecmTemplate);
                   
               }
               else{
                   console.log( "ecmTemplate " + ecmTemplateName + " in else" );
                   this.ecmTemplate = ECM_TEMPLATES[ecmTemplateName];
               }    
                   this.ecmTemplate.setItemDetail( this.itemDetail );
               
               if(this.itemDetail.itemSubCategory){
                   this.scatCode = this.itemDetail.itemSubCategory.scatCode;
                }
                   this.noOfReviews = this.itemDetail.itemRatings.NO_OF_REVIEWS;
                   
                   let breadcrumb = [{label: 'Home', url: '/home'}, {label: this.itemDetail.itemCategory.shDescr,url: '/categories/' + this.itemDetail.itemSubCategory.catCode},{label: this.itemDetail.itemSubCategory.shDescr,url: '/products/' + this.itemDetail.itemSubCategory.scatCode}];
                   this.breadcrumbSerivce.breadcrumbs = breadcrumb;
    
                   console.log( "Changed scatCode.." + this.scatCode );
               

               if ( this.ecmTemplate ) {
                   console.log('template----',this.ecmTemplate);   
                  // this.ecmTemplate.setItemDetail( this.itemDetail );
               }
               else {
                   //alert( "Sorry, the " + ecmTemplateName + " is not in the system yet!" );
               }
           }
           });
  }
  
  scrollToReviews() {
      let offsetTop = this.reviewsAndRating.nativeElement.offsetTop;
      console.log(' scrollToReviews:: offsetTop >>' + offsetTop);
      window.scrollTo(0, offsetTop - 80); 
  }

  doActivity($event) {
    this.performActivity($event.activity, $event.data, $event);
  }

  performActivity(activity: string, data: any, $event) {
    console.log( 'doActivity > > ' , activity, data, $event.caller, $event.callBack );
    if( activity == 'ADD_CART' ) {
        if( data.isAddToCart ) { //GO TO CART
            this.router.navigate(['/cart']);
        }
        else {                  //ADD TO CART
            this.addToCart(data.item);
            this.showSnackbar('Item Added to your Cart');
        }
    }
    else if( activity == 'ADD_WISHLIST' ) {
       
        if(this.checkUser() !== 'undefined' && this.checkUser() !== null && this.checkUser() !== 'null')
        {
            this.addToWishlist(data.item);
            $event.caller[$event.callBack]();
            this.showSnackbar('Item Added to your Wishlist');
        }
        else
        {
            this.showSignInPanel();
        }
    }
    else if( activity == 'REMOVE_WISHLIST' ) {
            this.removeFromWishlist(data.item);
            this.showSnackbar('Item Removed from your Wishlist');
    }
    else if( activity == 'BOOK_NOW' ) {
        this.showSnackbar('Book Now - Redirect to Checkout');
    }
    else if( activity == 'BUY_NOW' ) {
//        if( !data.isAddToCart ) { //ADD TO CART
//            this.addToCart(data.item);
//            this.showSnackbar('Item Added to your Cart');
//        }
        this.checkOutService.setItem(data.item);
        this.router.navigate(['/checkout']);
    }
    else if(activity == 'SHOW_SIGNIN_PANEL'){
        this.showSignInPanel();
    }
  }

  addToCart(item) {
    item.itemQuantity = 1;
    this.store.dispatch(this.cartActions.addToCartSuccess(item));
  }

  addToWishlist( item ) {
    this.store.dispatch(this.wishListAction.addToWishlistSuccess(item));
  }

  removeFromWishlist( item ) {
      this.store.dispatch(this.wishListAction.deleteWishlistItemSuccess(item));
  }

  showSnackbar( message ) {
      this.snackBar.open( message, '', { duration: 2000 });
  }
  
  storeCatSubcat()
  {
      let category = this.itemDetail.itemCategory;
      if( category ) {
          this.store.dispatch({type: 'CATEGORY', payload: category});  
      }
      
      let subCategory = this.itemDetail.itemSubCategory;
      if( subCategory ) {
          this.store.dispatch({type: 'SUB_CATEGORY', payload: subCategory});  
      }
  }
  
  showSignInPanel()
  {
      console.log('showSignin');
      this.header.userAction();
  }
  
  checkUser(){
      var userInfo = localStorage.getItem( 'userInfo' );
      if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' ) 
      {
          return userInfo;
      }
      else 
      {
          return userInfo;
      }
  }
  
  openReviewDialog(userInfo){
      console.log("Complete Fecth Review");

      if( this.clientWidth < 640 )
      {
              this.ecmPanel.open({ type: 'overlay', option: 'WRITE_REVIEW_OPT', top:'0px', left: '0px', width:'100%', height: '100%', data: { detail: this.itemDetail,userId: JSON.parse(this.checkUser()).LOGIN_CODE, userReview: this.userReview} });
      }
      else 
      {
              this.ecmPanel.open({ type: 'overlay', option: 'WRITE_REVIEW_OPT', top:'100px', left: '20%', width:'60%', height: '535px', data: { detail: this.itemDetail,userId: JSON.parse(this.checkUser()).LOGIN_CODE, userReview: this.userReview} });
      }  
  }  
  
  getAttributeType(itemCode){
      this.itemDetail.itemVariants.forEach(
              value => { 
                  if(value.variants){   
                       this.attribCode = value.attribCode;
                       let variant = value.variants.find(x => x.itemCode === itemCode);
                       this.attribVal = variant.value;
                  }
              });
  }
}
