import { Directive, ViewContainerRef,TemplateRef,OnInit,Input,OnDestroy } from '@angular/core';
import { Store} from '@ngrx/store';
import * as appCommonReducer from '../../reducers/app-common.reducer'
import { IPackages } from '../../models/package';
import { Observable, Subscription } from 'rxjs';

@Directive({
  selector: '[fmHasPackage]',
})
export class HasPackageDirective  implements OnDestroy{
  @Input()
  set fmHasPackage(packageIdentifier:string) {
    this.packageIdentifier$ = packageIdentifier;
    this.updateView(); 
  }

  @Input()
  set fmHasPackageThen(thenTemplate:TemplateRef<any>) {
    this.thenTemplate$ = thenTemplate;
    this.updateView(); 
  }

  @Input()
  set fmHasPackageElse(thenTemplate:TemplateRef<any>) {
    this.elseTemplate$ = thenTemplate;
    this.updateView(); 
  }

  private packageIdentifier$:string;
  private thenTemplate$:TemplateRef<any>;
  private elseTemplate$:TemplateRef<any>;
  private packages$:any = {};
  private packagesObservable$:Observable<IPackages> = this.store$.select(appCommonReducer.SelectGetUserPackages);
  private packSub:Subscription;

  constructor(private templateRef$: TemplateRef<any>,private viewContainerRef$: ViewContainerRef,private store$: Store<appCommonReducer.State>) { 
    this.thenTemplate$=templateRef$;
    this.packSub = this.store$.select(appCommonReducer.SelectGetUserPackages).subscribe((packages) => {
      this.packages$ = packages;
        this.updateView();     
    });
    this.updateView(); 
  }


  updateView() {
    this.viewContainerRef$.clear();
    const today = new Date(new Date(Date.now()).toUTCString()).setHours(0, 0, 0, 0);
    if (this.packages$[this.packageIdentifier$] &&
      (this.packages$[this.packageIdentifier$].dataDate && new Date(this.packages$[this.packageIdentifier$].dataDate).setHours(0, 0, 0, 0) <= today) &&
      (this.packages$[this.packageIdentifier$].dataEndDate == null || new Date(this.packages$[this.packageIdentifier$].dataEndDate).setHours(0, 0, 0, 0) >= today)) {
      this.viewContainerRef$.createEmbeddedView(this.thenTemplate$);
    } else if (this.elseTemplate$) {
      this.viewContainerRef$.createEmbeddedView(this.elseTemplate$);
    } 
  }

  ngOnDestroy() {
    if(this.packSub) this.packSub.unsubscribe();
  }
}