import { Component, Input, OnInit, ComponentFactoryResolver, ViewChild, SimpleChanges, ComponentFactory, Inject} from '@angular/core';
import { Feature } from 'ol';
import { Geometry} from 'ol/geom';
import { FeatureListComponent,AbstractFeatureListComponent } from '../feature-list/feature-list.component';
import { WidgetHostDirective } from '../widget-host/widget-host.directive';
import  {IQueryState,PackageService } from '@farmmaps/common';
import * as mapReducers from '../../reducers/map.reducer';
import * as mapActions from '../../actions/map.actions';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';


@Component({
    selector: 'fm-map-feature-list-container',
    templateUrl: './feature-list-container.component.html',
    styleUrls: ['./feature-list-container.component.scss'],
    standalone: false
})
export class FeatureListContainerComponent {

  constructor(private store: Store<mapReducers.State>,private componentFactoryResolver: ComponentFactoryResolver, @Inject(AbstractFeatureListComponent) public featureLists: AbstractFeatureListComponent[],private packageService:PackageService ) {
    this.featureLists = [...this.featureLists].reverse();
  }

  @Input() features: Array<Feature<Geometry>>
  @Input() queryState: IQueryState;
  @Input() selectedFeature: Feature<Geometry>;
  @Input() clickedFeature:Observable<Feature<Geometry>>;

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

  loadComponent(queryState:IQueryState) {
    let componentFactory: ComponentFactory<AbstractFeatureListComponent> = this.componentFactoryResolver.resolveComponentFactory(FeatureListComponent); // default
    let selected = -1;
    let maxMatches =0;
    const showItem = true;
    for (let i = 0; i < this.featureLists.length; i++) {
      let matches=0;
      let criteria=0;
      if (this.featureLists[i]['forItemType']) {
        criteria++;
        if( this.featureLists[i]['forItemType'].split(",").filter(part => part == queryState.itemType).length == 1) {
          matches++;
        }
      }
      if(this.featureLists[i]['forChild'] ) {
        criteria++;
        if(queryState.parentCode && queryState.parentCode != "") {
          matches++;
        }
      }     
      if(criteria == matches && matches > maxMatches) {
        selected=i;
        maxMatches = matches;
      }
    }
    if (selected >= 0) {
      componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.featureLists[selected]['constructor'] as any);
      if (this.featureLists[selected]['collapseSearch'] === true) {
        this.store.dispatch(new mapActions.CollapseSearch());
      }     
    }
    const viewContainerRef = this.widgetHost.viewContainerRef;
    viewContainerRef.clear();
    if(showItem) {
      this.componentRef = viewContainerRef.createComponent(componentFactory);
      (<AbstractFeatureListComponent>this.componentRef.instance).features = this.features;
      (<AbstractFeatureListComponent>this.componentRef.instance).queryState = this.queryState;
      (<AbstractFeatureListComponent>this.componentRef.instance).selectedFeature = this.selectedFeature;
    }    
  }

  ngOnInit() {
    this.clickedFeature.subscribe((feature => {
      (<AbstractFeatureListComponent>this.componentRef.instance).handleFeatureClick(feature);
    }));
  }

  ngOnChanges(changes: SimpleChanges) {
    if ((changes["queryState"] && changes["queryState"].currentValue)) {
        this.loadComponent(changes["queryState"].currentValue);
    }
    if ((changes["features"] && changes["features"].currentValue)) {
      (<AbstractFeatureListComponent>this.componentRef.instance).features = changes["features"].currentValue;
      this.componentRef.changeDetectorRef.detectChanges();
    }
    if(changes["selectedFeature"]) {
      (<AbstractFeatureListComponent>this.componentRef.instance).selectedFeature = changes["selectedFeature"].currentValue;
      this.componentRef.changeDetectorRef.detectChanges();
    }
  }
}
