import {AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {select, Store} from '@ngrx/store';
import {Observable} from 'rxjs/Observable';
import {<%= pascalCase(pluralActionName) %>Actions} from '../../store/<%= paramCase(pluralActionName) %>/<%= paramCase(pluralActionName) %>.actions';
import {<%= pascalCase(actionName) %>} from '../../store/<%= paramCase(pluralActionName) %>/<%= paramCase(pluralActionName) %>.domain';
import {selectCurrent<%= pascalCase(actionName) %>} from '../../store/<%= paramCase(pluralActionName) %>/<%= paramCase(pluralActionName) %>.selectors';

@Component({
  selector: 'app-<%= paramCase(componentName) %>',
  templateUrl: './<%= paramCase(componentName) %>.component.html',
  styleUrls: ['./<%= paramCase(componentName) %>.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class <%= pascalCase(componentName) %>Component implements OnInit, AfterViewInit, OnDestroy  {
  current<%= pascalCase(actionName) %>$: Observable<<%= pascalCase(actionName) %>>;

  constructor(private cdRef: ChangeDetectorRef,
              private route: ActivatedRoute,
              private router: Router,
              private store: Store<any>) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      const id = +params['id'];
      if (id) {
        this.store.dispatch(new <%= pascalCase(pluralActionName) %>Actions.SetCurrentId(id));
        this.store.dispatch(new <%= pascalCase(pluralActionName) %>Actions.FetchOneRemoteRequest(id));
      } else {
        this.router.navigateByUrl('<%= notFoundUrl %>').catch((err: any) => console.error(err));
      }
    });
    this.current<%= pascalCase(actionName) %>$ = this.store.pipe(select(selectCurrent<%= pascalCase(actionName) %>));
  }

  ngAfterViewInit(): void {
    this.cdRef.markForCheck();
  }

  ngOnDestroy() {
    this.store.dispatch(new <%= pascalCase(pluralActionName) %>Actions.ClearCurrentId());
  }
}
