import { Component, OnInit, HostListener } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppState } from '../../ecm-store/reducers';
import { CategoryActions, SubCategoryActions } from '../../ecm-store/actions';

import { ScrollService } from '../../scroll.service';
import { Category } from '../../ecm-model/category-model';

import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'ecm-category',
  templateUrl: './ecm-category.component.html',
  styleUrls: ['./ecm-category.component.css']
})
export class EcmCategoryComponent implements OnInit {
    errorMessage: string;
    selectedPlace = 'Mumbai';
    categories: Observable<Category[]>;
    position: any;;
    
    @HostListener("window:scroll", [])
      onWindowScroll() { 
      this.position=window.pageYOffset; 
    }
    
    constructor(private scroll_service: ScrollService, private store: Store<AppState>, private categoryAction:CategoryActions, private subCategoryAction: SubCategoryActions) { }
    
    ngOnInit() {
      this.getCategories();
    }
    
    ngOnDestroy() {
      this.scroll_service.setCatPos(this.position);
    }
    
    ngAfterViewInit() {
      var pos=this.scroll_service.getCatPos();    
      window.scrollTo(0,pos); 
      console.log("AfterContenet Init of Category");   
    }
    
    getCategories() {
        this.categories = this.store.select('categories');
    }
    
    storeCategory(selectedCategory) {
      this.store.dispatch( this.subCategoryAction.resetSubCategoryList() );
      this.store.dispatch( this.subCategoryAction.loadSubCategories( selectedCategory.catCode ) );
      this.store.dispatch(this.categoryAction.getCategorySuccess(selectedCategory));
    }

}
