import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { Observable, BehaviorSubject, Subject, EMPTY, of } from 'rxjs'
import { catchError, map , takeUntil } from 'rxjs/operators'

import { MessageService } from './message.service'
import { Plant, Plants } from './models'

@Injectable({
  providedIn: 'root'
})
export class PlantekeyService {
  public stopRequest: Subject<void> = new Subject<void>()
  public plants: BehaviorSubject<Plants> = new BehaviorSubject<Plants>({})

  constructor(
    public httpClient: HttpClient,
    public messageService: MessageService,
  ) {
    this.stopRequest.subscribe(_=>this.messageService.spinner.next(false))
  }

  getAllPlants(): Observable<Plants> {
    this.messageService.spinner.next(true)
    return this.httpClient
      .get<Plant[]>('v1/plantekey/details')
      .pipe(takeUntil(this.stopRequest))
      .pipe(
        map(
          plantList => {
            this.messageService.spinner.next(false)
            let plants: Plants = {}
            plantList.forEach(
              p =>
                plants[p.id] = new Plant(
                  p['ID'],
                  p['id'],
                  p['english'],
                  p['family'],
                  p['hindi'],
                  p['img'],
                  p['name'],
                  p['spiritual'],
                  p['tamil'],
                  p['type'],
                  p['description'],
                  p['habit'],
                  p['landscape'],
                  p['uses'],
                  p['planting'],
                  p['propagation'],
                  p['element'],
                  p['woody'],
                  p['latex'],
                  p['leaf_style'],
                  p['leaf_type'],
                  p['leaf_arrangement'],
                  p['leaf_aroma'],
                  p['leaf_length'],
                  p['leaf_width'],
                  p['flower_color'],
                  p['flower_aroma'],
                  p['flower_size'],
                  p['fruit_color'],
                  p['fruit_size'],
                  p['fruit_type'],
                  p['thorny'],
                  p['images'],
                  p['symbol'],
                )
            )
            this.plants.next(plants)
            this.plants.complete()
            return plants
          }
        ),
        catchError(
          (err, caught) => {
            console.error(err, caught)
            this.messageService.message.next(`Network issue (${err.status})`)
            this.messageService.spinner.next(false)
            return EMPTY
          }
        )
      )
  }
}
