import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MdSnackBar } from '@angular/material';
import { Store } from '@ngrx/store';
import {AppState} from '../ecm-store/reducers';

import { ECMCard } from '../ecm-model/card-model';
import { Category } from '../ecm-model/category-model';
import { SubCategory } from '../ecm-model/subcategory-model';
import { ItemDetail } from '../ecm-model/product-detail-model';
import { Reviews } from '../ecm-model/product-review.model';

import { EcmProductReviewService } from '../ecm-product-details/ecm-product-review.service';
import {EcmProductDetailService} from '../ecm-product-details/ecm-product-detail.service'
import { Observable } from 'rxjs/Observable';
import { Item } from '../ecm-model/product-model';
import { Order } from '../ecm-model/order-model';
import { ItemActions } from '../ecm-store/actions';

@Component({
  selector: 'ecm-card',
  templateUrl: './ecm-card.component.html',
  styleUrls: ['./ecm-card.component.css']
})

export class ECMCardComponent implements OnInit {
  @Input() card: ECMCard;
  @Input() category: Category;
  @Input() subcategory: SubCategory;
  @Input() itemData: ItemDetail;  
  @Input() extraParam: any;
  @Input() reviewsData: Reviews;
  @Input('trendImg') trendImg: boolean;
  @Input() orderDetails: Order;
  inWishlist: boolean;
  
  @Output() storeData = new EventEmitter();
  @Output() addToWishlist = new EventEmitter();
  @Output() removeFromWishlist = new EventEmitter();
  
  itemCode: any;
  itemDetail: ItemDetail;
  wishlistItems: Observable<Item[]>;
  categoryList: any;
  IS_WISHLIST: boolean;
  constructor(private route: ActivatedRoute,private router: Router, private productDetailService: EcmProductDetailService, private productReviewService: EcmProductReviewService, private store: Store<AppState>, private itemAction: ItemActions, public snackBar: MdSnackBar,) { 
  
  }

  ngOnInit() {
      console.log('order detail in ecm-card :---',this.orderDetails);
      if(this.itemData){
          this.wishlistItems = this.store.select('wishlistItems');
          this.wishlistItems.subscribe( wishlistItems => {
              if(wishlistItems.find(x => x.itemCode === this.itemData.itemCode))
                  this.inWishlist = true;
              else
                  this.inWishlist = false;
          } );
      }
      let openRoutePath = this.route.snapshot.url[0].path;
      if(openRoutePath == 'wishlist'){
          this.IS_WISHLIST = true;
      }
      let menu : Observable<any> = this.store.select('menuList');
      menu.subscribe( menuList => {
          this.categoryList = menuList.summary;
          console.log('menuList.summary',menuList,  menuList.summary);
      });
    
      if(this.orderDetails){
          this.productDetailService.getItemDetail(this.orderDetails.itemCode).subscribe(
                  itemDetail => {
                      this.itemDetail = itemDetail;
                  }
          );
          
      }
  }

   viewItem(){      
      // this.recentviewService.storeRecentViewItem(this.itemData.itemCode);      
       this.storeData.emit(this.itemData);
       this.router.navigate(['/detail',this.itemData.itemCode]);
   }
  
   createRatings(ratings){
     var rating: number[] = [];
     for(var i = 1; i <= ratings; i++){
      rating.push(i);
     }
     return rating;
   }
   
   viewCategories(){
       
       let cat = this.categoryList.find( category => category.catCode === this.category.catCode);
       console.log( this.categoryList, cat );  
       if( cat && !cat.subcategory ){
           this.store.dispatch( this.itemAction.loadItems( this.category.catCode ) );
           this.router.navigate([ '/products', this.category.catCode]);
       }
       else {
           this.storeData.emit(this.category);
           this.router.navigate([ '/categories', this.category.catCode]);
       }
       
   }
   
   viewProducts(){
     this.storeData.emit(this.subcategory);
     this.router.navigate([ '/products', this.subcategory.scatCode]);
   }

   updateLikes(item_code) {
       if(this.isAuthUser())
       {
         let likesData ="{\"userId\":\""+this.reviewsData.userId+"\",\"productUsfulCnt\":\""+(this.reviewsData.productUsfulCnt+1)+"\",\"productNotUsfulCnt\":\""+this.reviewsData.productNotUsfulCnt+"\"}";       
         console.log("Likes Data-->");
         console.log(likesData);       
         this.productReviewService.updateLikes(item_code, likesData);
       }
       else 
       {
         alert("Please Login First.");   
       }
   }
   
   updateDislikes(item_code) {  
       if(this.isAuthUser())
       {
         let likesData ="{\"userId\":\""+this.reviewsData.userId+"\",\"productUsfulCnt\":\""+this.reviewsData.productUsfulCnt+"\",\"productNotUsfulCnt\":\""+(this.reviewsData.productNotUsfulCnt-1)+"\"}";
         console.log("Likes Data-->");
         console.log(likesData);
         this.productReviewService.updateLikes(item_code, likesData);
       }
       else 
       {
         alert("Please Login First.");   
       }
   }
   
   isAuthUser(){
       var isAuthUser;
       var userInfo = localStorage.getItem( 'userInfo' );
       console.log( 'EcmUserOptionComponent getUserInfo ::' + userInfo );
       if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' )
       { 
           isAuthUser = true;
       }
       else
       {
           isAuthUser = false;
       }
       return isAuthUser;
   }
 
   ////////////////////////////////////  FOR ORDERS        ////////////////////////////////////////////
   
   cancelOrder(){
       this.openSnackBar( 'The Order has been canceled' );
   }
   openSnackBar( message: string ) {
       this.snackBar.open( message, '', {
           duration: 2000,
       });
   }
   
   
   
   
   
}
