import { Component, Input, Injectable, Inject, Optional,ComponentFactoryResolver, ViewContainerRef, QueryList, ComponentFactory, ViewChildren,AfterViewInit } from '@angular/core';
import { Location } from '@angular/common';
import { Store } from '@ngrx/store';
import * as mapReducers from '../../reducers/map.reducer';
import { commonReducers,ItemTypeService, IItem, Item,IListItem } from '@farmmaps/common';
import { AbstractItemWidgetComponent } from '../item-list-item/item-list-item.component';


@Injectable()
@Component({
    selector: 'fm-map-item-widget-list',
    templateUrl: './item-widget-list.component.html',
    styleUrls: ['./item-widget-list.component.scss'],
    standalone: false
})
export class ItemWidgetListComponent implements AfterViewInit {

  @Input() item: IListItem;
  public widgets: AbstractItemWidgetComponent[];
  @ViewChildren('widgetTemplate', { read: ViewContainerRef }) private widgetTargets: QueryList<ViewContainerRef>;

  constructor(public store: Store<mapReducers.State | commonReducers.State>, public itemTypeService: ItemTypeService, public location: Location, private componentFactoryResolver: ComponentFactoryResolver, @Optional() @Inject(AbstractItemWidgetComponent) itemWidgetComponentList: AbstractItemWidgetComponent[]) {
    this.widgets = itemWidgetComponentList; //todo filter this list on widgets available for user 
  }

  ngAfterViewInit() {
    const targets = this.widgetTargets.toArray();
    if(this.widgets) {
      for (let i = 0; i < this.widgets.length; i++) {
        const componentFactory: ComponentFactory<AbstractItemWidgetComponent> = this.componentFactoryResolver.resolveComponentFactory(this.widgets[i]['constructor'] as any);
        const viewContainerRef = targets[i];
        viewContainerRef.clear();
  
        const componentRef = viewContainerRef.createComponent(componentFactory);
        (<AbstractItemWidgetComponent>componentRef.instance).item = this.item;
      }  
    }
  }
}
