import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject, Type} from '@angular/core';
import { AbstractItemListItemComponent,ItemListItemComponent } from '../item-list-item/item-list-item.component';
import { WidgetHostDirective } from '../widget-host/widget-host.directive';
import { IItem, IListItem } from '@farmmaps/common';


@Component({
    selector: 'fm-map-item-list-item-container',
    template: `
              <div style="height:100%">
                 <ng-template fm-map-widget-host></ng-template>
              </div>
            `,
    standalone: false
})
export class ItemListItemContainerComponent {

  constructor(private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractItemListItemComponent) public itemComponentList: AbstractItemListItemComponent[] ) {
    this.itemComponentList = [...this.itemComponentList].reverse();
  }

  @Input() item: IListItem;

  @ViewChild(WidgetHostDirective, { static: true }) widgetHost: WidgetHostDirective; 

  loadComponent() {
    let componentFactory: ComponentFactory<AbstractItemListItemComponent> = this.componentFactoryResolver.resolveComponentFactory(ItemListItemComponent); // default

    let selected = -1;
    let maxMatches =0;
    const showItem = true;
    for (let i = 0; i < this.itemComponentList.length; i++) {
      let matches=0;
      let criteria=0;
      if (this.itemComponentList[i]['forItemType']) {
        criteria++;
        if(this.itemComponentList[i]['forItemType'].split(",").filter(part => part ==this.item.itemType).length == 1) {
          matches++;
        }
      }
      if (this.itemComponentList[i]['forSourceTask']) {
        criteria++;
        if(this.itemComponentList[i]['forSourceTask'].split(",").filter(part => part ==this.item.sourceTask).length ==1) {
          matches++;
        }
      }
        
      if(criteria == matches && matches > maxMatches) {
        selected=i;
        maxMatches = matches;
      }
    }
    if (selected >= 0) {
      componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.itemComponentList[selected]['constructor'] as any);         
    }
    
    const viewContainerRef = this.widgetHost.viewContainerRef;
    viewContainerRef.clear();

    const componentRef = viewContainerRef.createComponent(componentFactory);
    (<AbstractItemListItemComponent>componentRef.instance).item = this.item;
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes["item"] && changes["item"].currentValue) {
        this.loadComponent();
    }
  }
}
