import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { HeroeModel } from '../models/heroe.model';
import { map } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';

@Injectable({
  providedIn: 'root',
})
export class HeroesService {
  private url = 'https://crud-angular-93dfc-default-rtdb.firebaseio.com';
  constructor(private http: HttpClient, private _snackBar: MatSnackBar) {}

  crearHeroe(heroe: HeroeModel) {
    return this.http.post(`${this.url}/heroes.json`, heroe).pipe(
      map((resp: any) => {
        heroe.id = resp.name;
        this._snackBar.open('Registro exitoso', 'Cerrar', {
          duration: 3000,
        });
        return heroe;
      })
    );
  }

  actualizarHeroe(heroe: HeroeModel) {
    const heroeTemp = {
      ...heroe,
    };

    delete heroeTemp.id;
    this._snackBar.open('Registro exitoso', 'Cerrar', {
      duration: 3000,
    });
    return this.http.put(`${this.url}/heroes/${heroe.id}.json`, heroeTemp);
    
  }

  getHeroes() {
    return this.http.get(`${this.url}/heroes.json`).pipe(
      map((result: any) => {
        if (result === null) return [];
        return Object.keys(result).map((key) => {
          const hero: HeroeModel = result[key];
          hero.id = key;
          return hero;
        });
      })
    );
  }

  getHeroe( id:string){
    return this.http.get(`${ this.url }/heroes/${ id }.json`)
  }

  deleteHeroe( id:string){
    this._snackBar.open('Registro exitoso', 'Cerrar', {
      duration: 3000,
    });
    return this.http.delete(`${ this.url }/heroes/${ id }.json`);
  }
}
