/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controladores;

import javax.annotation.Resource;
import materiales.IMaterialRepository;
import modelo.MaterialForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import validacion.CodigoValidator;

/**
 *
 * @author armaf
 */
@Controller
@RequestMapping(value = "/material")
public class MaterialController {
    //@Autowired
    @Resource(name ="repoMaterial")
    private IMaterialRepository repo;    
    
    @RequestMapping(method = RequestMethod.GET)
    public String listado(Model model) {
        model.addAttribute("material", MaterialForm.convertir(repo.getMaterial()));
        return "listado";
    }
    
    @RequestMapping(value="eliminar/{codigo}", method = RequestMethod.GET)
    public String eliminar(Model model, @PathVariable(value="codigo") int codigo) {
        repo.eliminarMaterial(codigo);
        String uriListado = "/mvc/material";
        return "redirect:"+uriListado;
    }
    
    @RequestMapping(value="add", method = RequestMethod.GET)
    public String altaMaterial(Model model) {
        model.addAttribute("material", new MaterialForm(0, "[Nombre]", 1.0));
        return "altaMaterial";
    }
    
    @Autowired
    private CodigoValidator validadorCodigo;
    
    @RequestMapping(value="add", method = RequestMethod.POST)
    public String altaMaterial(Model model,
            @Validated @ModelAttribute("material") MaterialForm material, Errors errores) {
        validadorCodigo.validate(material.getCodigo(), errores); 
        if (errores.hasErrors()) {
            return "altaMaterial";
        }
        repo.insertar(MaterialForm.convertir(material));
        String uriListado = "/mvc/material";
        return "redirect:"+uriListado;
    }
    
}
