import { Component, Input, Injectable,Directive,SimpleChanges } from '@angular/core';
import { Location } from '@angular/common';
import { Feature } from 'ol';
import { Geometry} from 'ol/geom';
import { Store,Action} from '@ngrx/store';
import * as mapReducers from '../../reducers/map.reducer';
import { commonReducers,ItemTypeService, IItem, Item } from '@farmmaps/common';
import * as mapActions from '../../actions/map.actions';
import { Observable, from } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { tassign } from 'tassign';
import { IQueryState } from '@farmmaps/common';


@Injectable()
@Directive()
export abstract class AbstractFeatureListComponent {
  @Input() features: Array<Feature<Geometry>>;
  @Input() queryState: IQueryState;
  @Input() selectedFeature: Feature<Geometry>;
  constructor(public store: Store<mapReducers.State | commonReducers.State>, public itemTypeService: ItemTypeService, private location: Location) {
  }

  handleFeatureClick(feature:Feature<Geometry>) {
    if(feature) {
      this.store.dispatch(new mapActions.ClickFeature(feature));
      const action = this.getAction(feature);
      this.store.dispatch(action);
    }
  }

  getAction(feature:Feature<Geometry>):Action {
      const newQuery: any = tassign(mapReducers.initialState.queryState);
      newQuery.parentCode = feature.get('parentCode');
      newQuery.itemCode = feature.get('code');
      newQuery.itemType = feature.get('itemType');
      return new mapActions.DoQuery(newQuery)  
  }

  handleFeatureMouseEnter(feature) {
    this.store.dispatch(new mapActions.SelectFeature(feature));
  }

  handleFeatureMouseLeave(feature) {
    this.store.dispatch(new mapActions.SelectFeature(null));
  }

  handleBackClick(event: MouseEvent) {
    event.preventDefault();
    this.location.back();
  }

  isFeatureSelected(feature:Feature<Geometry>):boolean {
    if(!this.selectedFeature) return false;
    return feature.getId() == this.selectedFeature.getId();
  }  
}

@Injectable()
@Component({
  selector: 'fm-map-feature-list',
  templateUrl: './feature-list.component.html',
  styleUrls: ['./feature-list.component.scss']
})
export class FeatureListComponent extends AbstractFeatureListComponent {

  constructor(store: Store<mapReducers.State | commonReducers.State>, itemTypeService: ItemTypeService,location:Location) {
    super(store, itemTypeService,location);
  }
}
