import { Component, Input,
  ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core'
import { ActivatedRoute, Params, Router } from '@angular/router'

import length from '@turf/length'

import { Trail, Tree, TreeTrail, Plant } from '../models'
import { DataService } from '../data.service'
import { ActionService } from '../action.service'
import { flipAnimation } from '../map/animation'

@Component({
  selector: 'app-trail-list-item',
  templateUrl: './trail-list-item.component.html',
  styleUrls: ['./trail-list-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [flipAnimation],
})
export class TrailListItemComponent {
  @Input() trail: Trail
  @Input() withMapButton: Boolean = true
  trees: Tree[] = []
  //treeBucket: {[plantekeyId: string]: Tree[]} = {}

  constructor(
    public dataService: DataService,
    public actionService: ActionService,
    protected router: Router,
    public cdr: ChangeDetectorRef,
  ) {}

  public isFlipped: boolean

  public flipCard(): void {
    this.isFlipped = !this.isFlipped;
  }

  showOnMap(trail: Trail) {
    this.router.navigate(['map'], trail.mapRouteArgs)
  }

  showDetails(trail: Trail) {
    this.router.navigate(['trail', trail.id])
  }

  onFileDropped(fileList: FileList) {
    const formData = new FormData()
    formData.set("file", fileList.item(0))
    this.actionService.upload('trail', 'photo', this.trail.id.toString(), formData).subscribe(
      res => {
        this.trail.photo = res['filename']
        this.cdr.markForCheck()
      }
    )
  }

  /*
  compute() {
    this.trees.forEach(
      tree => {
        if (!this.treeBucket[tree.plantekeyId]) {
          this.treeBucket[tree.plantekeyId] = []
        }
        this.treeBucket[tree.plantekeyId].push(tree)
      }
    )
    this.cdr.markForCheck()
  }
  */

  /*
  getTrees(): string {
    return Object.entries(this.treeBucket).map(
      ([plantekeyId, trees]) => `${trees[0].plant.english} (${trees.length})`
    ).join(', ')
  }
  */
}
