import { ChangeDetectorRef, Directive, ElementRef, Input, OnInit, ViewContainerRef } from '@angular/core';
import { IObjectController } from '../interfaces/object-controller';
import { DetailsComponentBase } from '../details-component-base';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { IAction } from '@objects-view/interfaces/actions/action';
import { AuthService } from '@shared/auth/auth.service';

@Directive({
  selector: '[appComponentHost]'
})
export class ComponentHostDirective implements OnInit {
  @Input() component;
  @Input() objectController: IObjectController;
  @Input() componentTabIndex: number;
  @Input() data?: Record<string, unknown>;
  @Input() detailsActions?: Array<IAction>;

  private componentInstance: DetailsComponentBase<IBaseFleioObjectModel>;

  constructor(
    private viewContainerRef: ViewContainerRef,
    public authSvc: AuthService,
    public elementRef: ElementRef,
    public changeDetectorRef: ChangeDetectorRef,
  ) {
  }

  dataChanged() {
    if (this.componentInstance) {
      this.componentInstance.dataChanged();
    }
  }

  ngOnInit(): void {
    this.viewContainerRef.clear();
    const componentRef = this.viewContainerRef.createComponent(this.component);
    if (this.objectController) {
      this.componentInstance = componentRef.instance as DetailsComponentBase<IBaseFleioObjectModel>;
      this.componentInstance.objectController = this.objectController;
      this.componentInstance.componentTabIndex = this.componentTabIndex;
      this.componentInstance.data = this.data;
      this.componentInstance.authSvc = this.authSvc;
      this.componentInstance.elementRef = this.elementRef;
      this.componentInstance.changeDetector = this.changeDetectorRef;
      this.componentInstance.detailsActions = this.detailsActions;
    }
  }
}
