package org.raliev.controllers;

import org.raliev.models.Pet;
import org.raliev.models.PetForm;
import org.raliev.store.Storages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Pet controller
 * @author raliev
 * @since 19.07.2017
 */
@Controller
@RequestMapping("/pet")
public class PetController {
    @Autowired
    private Storages storages;

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createGet(@RequestParam("id") String userId, ModelMap model) {
        model.addAttribute("userId", userId);
        return "pet/PetCreate";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createPost(@ModelAttribute PetForm pf) {
        Pet pet = new Pet(
                0,
                pf.getPetName(),
                Integer.valueOf(pf.getPetTypeId()),
                storages.userStorage.get(Integer.valueOf(pf.getUserId()))
        );
        this.storages.petStorage.add(pet);
        return "redirect:/user/edit?id=" + pet.getOwner().getId();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam("pid") String id) {
        Pet pet = this.storages.petStorage.get(Integer.valueOf(id));
        int userId = pet.getOwner().getId();
        this.storages.petStorage.delete(Integer.valueOf(id));

        return "redirect:/user/edit?id=" + userId;
    }
}