import {AfterViewInit, Directive, Input, OnDestroy, TemplateRef, ViewContainerRef} from '@angular/core';
import {Subscription} from 'rxjs';
import {PackageService} from '../../services/package.service';
import * as appCommonReducer from '../../reducers/app-common.reducer';
import {Store} from '@ngrx/store';

@Directive({
    selector: '[fmHasPackage]',
    standalone: false
})
export class HasPackageDirective implements OnDestroy, AfterViewInit {

  @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 packSub: Subscription;

  constructor(private hostTemplateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef,
              private store: Store<appCommonReducer.State>, private packageService: PackageService) {
    this.thenTemplate = hostTemplateRef;
    this.packSub = this.store.select(appCommonReducer.SelectGetValidUserPackages).subscribe((_) => {
      this.updateView();
    });
  }

  ngAfterViewInit() {
    this.updateView();
  }

  updateView() {
    this.viewContainerRef.clear();
    if (this.packageService.hasPackage(this.packageIdentifier)) {
      this.viewContainerRef.createEmbeddedView(this.thenTemplate);
    } else if (this.elseTemplate) {
      this.viewContainerRef.createEmbeddedView(this.elseTemplate);
    }
  }

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