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: '[fmPackageExists]',
    standalone: false
})
export class PackageExistsDirective implements OnDestroy, AfterViewInit {

  @Input()
  set fmPackageExists(packageIdentifier: string) {
    this.packageIdentifier = packageIdentifier;
    this.updateView();
  }

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

  @Input()
  set fmPackageExistsElse(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.SelectGetPackages).subscribe((_) => {
      this.updateView();
    });
  }

  ngAfterViewInit() {
    this.updateView();
  }

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

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