import {inject, Injectable} from '@angular/core';
import {Monster} from '../../models/monster.model';
import {HttpClient} from '@angular/common/http';
import {IMonster} from '../../interfaces/monster';
import {map, Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MonsterService {

  private readonly http: HttpClient = inject(HttpClient);
  private readonly BASE_URL = 'http://localhost:8000/monsters/';

  getAll(): Observable<Monster[]> {
    return this.http.get<IMonster[]>(this.BASE_URL).pipe(
      map((monsters: IMonster[]) => {
        return monsters.map(monsterJson => Monster.fromJson(monsterJson));
      })
    )
  }

  get(id: number): Observable<Monster> | undefined {
    return this.http.get<IMonster>(this.BASE_URL + id + '/').pipe(
      map((monsterJson: IMonster) => {
        return Monster.fromJson(monsterJson);
      })
    );
  }

  add(monster: Monster): Observable<Monster> {
    return this.http.post<IMonster>(this.BASE_URL,  monster.toJson()).pipe(
      map((monsterJson: IMonster) => {
        return Monster.fromJson(monsterJson);
      })
    );
  }

  update(monster: Monster): Observable<Monster> {
    return this.http.put<IMonster>(this.BASE_URL + monster.id + '/', monster.toJson()).pipe(
      map((monsterJson: IMonster) => {
        return Monster.fromJson(monsterJson);
      })
    );
  }

  delete(id: number): Observable<void> {
    return this.http.delete<void>(this.BASE_URL + id + '/');
  }
}
