import { ComponentFactoryResolver, Directive, Input, OnChanges, OnInit, ViewContainerRef } from '@angular/core';
import { IPluginComponent } from '../interfaces/plugin-component';

@Directive({
  selector: '[appPluginComponentHost]'
})
export class PluginComponentHostDirective implements OnInit, OnChanges {
  @Input() component;
  @Input() data: object;

  private componentInstance: IPluginComponent;

  constructor(
    private viewContainerRef: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) {
  }

  ngOnInit(): void {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.component);
    this.viewContainerRef.clear();

    const componentRef = this.viewContainerRef.createComponent(componentFactory);
    this.componentInstance = componentRef.instance as IPluginComponent;
    this.componentInstance.data = this.data;
  }

  ngOnChanges() {
    if (this.componentInstance?.dataChanged) {
      this.componentInstance.data = this.data;
      this.componentInstance.dataChanged();
    }
  }

  setErrors(errors: Record<string, any>) {
    if (this.componentInstance?.setFormErrors) {
      this.componentInstance.setFormErrors(errors);
    }
  }
}
