import { Component, OnInit } from '@angular/core';
import {PetModel} from '../../models/pet.model';
import {PetsService} from '../../services/pets.service';
import {map, mergeMap} from 'rxjs/operators';
import {ActivatedRoute, Router} from '@angular/router';


@Component({
  selector: 'app-pets-main',
  templateUrl: './pets-main.component.html',
  styleUrls: ['./pets-main.component.scss']
})
export class PetsMainComponent implements OnInit {
  public id : number
  public activePet: PetModel;
  public pets: PetModel[];

  constructor(
    private readonly petsService: PetsService,
    private route: ActivatedRoute,
    private readonly router: Router
  ) { 
    this.pets = [];
    this.clearActivePet()
  }

  ngOnInit() {
    this.id = this.route.snapshot.params.person;
    this.petsService.list(this.id)
      .subscribe(pets => this.pets = pets);
    
  }

  public onCleanForm(): void {
    this.clearActivePet();
  }

  public clearActivePet():void{
    this.activePet = { id: undefined, name: '', kind: '', owner: undefined };
  }

  public back(){
    this.router.navigate(['/']);
  }

  public onDelete(pet: PetModel): void {
    if (confirm(`¿Estás seguro de que deseas eliminar a ${pet.name}?`)) {
      this.petsService.delete(pet)
        .pipe(
          mergeMap(() => this.petsService.list(pet.owner))
        )
        .subscribe(pets => this.pets = pets);
    }
  }

  public onEdit(pet: PetModel): void {
    this.activePet = pet;
    console.log("Noe")
    console.log(this.activePet)
  }

  public onModifyForm(pet: PetModel): void {
    if (pet.id === undefined) {
      this.petsService.create(pet)
        .pipe(
          mergeMap(() => this.petsService.list(pet.owner))
        )
        .subscribe(pets => {
          this.pets = pets;
          this.clearActivePet();
        });
    } else {
      this.petsService.modify(pet)
        .pipe(
          mergeMap(() => this.petsService.list(pet.owner))
        )
        .subscribe(pets => {
          this.pets = pets;
          this.clearActivePet();
        });
    }
  }

}
