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

import { Tree } from '../models'
import { ActionService } from '../action.service'
import { flipAnimation } from '../map/animation'

@Component({
  selector: 'app-tree-popup',
  templateUrl: './tree-popup.component.html',
  styleUrls: ['./tree-popup.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [flipAnimation],
})
export class TreePopupComponent {
  @Input() tree: Tree
  public isFlipped: boolean

  constructor(
    public actionService: ActionService,
    private router: Router,
    public cdr: ChangeDetectorRef,
  ) {}

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

  navigateToDetail() {
    this.router.navigate(['tree', this.tree.id])
  }

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