import { Injectable, ComponentFactoryResolver, ViewContainerRef, Type } from '@angular/core';
import { DashboardComponentChart } from './widgets/dashboard-component-chart.component';
import { DashboardComponentTable } from './widgets/dashboard-component-table.component';
import { DashboardComponentAccordionTable } from './widgets/dashboard-component-accordion-table.component';

@Injectable({ providedIn: 'root' })
export class DashboardComponentFactoryService {
  // ComponentMap with all possible widgets.
  // Notes: The key is always lowercase
  private componentMap: { [key: string]: Type<any> } = {
    chart: DashboardComponentChart,
    table: DashboardComponentTable,
    accordion: DashboardComponentAccordionTable,
  };

  constructor(
    private resolver: ComponentFactoryResolver
  ) {}

  /**
   * data is a structure:
   * { dashboardComponent: <IDashboardComponent> }
   */
  createComponent(type: string, container: ViewContainerRef, data: any) {
    // componentMap key is always lowercase
    type = type.toLowerCase();
    
    // Get the component to draw
    const componentType = this.componentMap[type];
    if (componentType) {
      const factory = this.resolver.resolveComponentFactory(componentType);
      const componentRef = container.createComponent(factory);
      componentRef.instance.dashboardComponent = data.dashboardComponent; // Pass data to component
      componentRef.instance.periodVersionId = data.periodVersionId;
      componentRef.instance.showTitle = data.showTitle;
    }
  }
}