/*
 * Copyright (C) 2020 Robert Bosch GmbH Copyright (C) 2020 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import {
  ComponentFactory,
  ComponentFactoryResolver,
  ComponentRef,
  Directive,
  Input,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';
import { BciActivityIndicatorComponent } from '../../core/layout/bci-activity-indicator/activity-indicator.component';

@Directive({
  selector: '[bciActivityIndicator]',
})
export class ActivityIndicatorDirective {
  activityIndicatorFactory: ComponentFactory<BciActivityIndicatorComponent>;
  activityIndicatorComponent: ComponentRef<BciActivityIndicatorComponent>;

  constructor(
    private templateRef: TemplateRef<any>,
    private vcRef: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) {
    // Create resolver for activity indicator component
    this.activityIndicatorFactory =
      this.componentFactoryResolver.resolveComponentFactory(BciActivityIndicatorComponent);
  }

  @Input()
  set bciActivityIndicator(showActivityIndicator: boolean) {
    this.vcRef.clear();

    if (showActivityIndicator) {
      // create and embed an instance of the activity indicator component
      this.activityIndicatorComponent = this.vcRef.createComponent(this.activityIndicatorFactory);
    } else {
      // embed the contents of the host template
      this.vcRef.createEmbeddedView(this.templateRef);
    }
  }
}
