import { Injectable, NgZone } from '@angular/core'
import { MatDialog } from '@angular/material/dialog'
import { Subject } from 'rxjs'

import { LngLat } from 'maplibre-gl'

import { DataService, TreeDef } from '../../data.service'
import { PlantChooserDialogComponent } from './plant-chooser-dialog'

@Injectable({
  providedIn: 'root'
})
export class MapEditService {
  public active: boolean = false
  public treeDef: TreeDef
  constructor(
    public ngZone: NgZone,
    public dataService: DataService,
    public dialog: MatDialog,
  ) {}

  public cancelEditMap$: Subject<void> = new Subject()

  toggle() {
    this.active = !this.active
  }

  addTree(lngLat: LngLat) {
    this.openDialog(lngLat)
  }

  openDialog(lngLat: LngLat) {
    this.ngZone.run(
      () => {
        const dialogRef = this.dialog.open(PlantChooserDialogComponent, {
          width: '24em',
          data: { plantId: undefined },
        })
        dialogRef.afterClosed().subscribe(result => {
          if (result) {
            this.setTreeDef(result['plant']['plantId'],
                            result['plant']['trails'])
            this.dataService.addTree(lngLat,
                                     this.treeDef,
                                     result['picture']['picture'],
                                     result['details'])
          }
          this.cancelEditMap$.next()
        })
      }
    )
  }

  setTreeDef(plantId: string, trailIds: string[]) {
    this.treeDef = new TreeDef(
      this.dataService.all.value.plants[plantId],
      trailIds.map(
        trailId => this.dataService.all.value.trails[trailId]
      )
    )
  }
}