/*
 * Copyright (C) 2017 Circulo Odontologico del Chaco
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ar.com.circuloodontochaco.co.controller.admin;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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 org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import ar.com.circuloodontochaco.co.dao.CodigoMovimientoRepository;
import ar.com.circuloodontochaco.co.dao.CodigoRetencionATPRepository;
import ar.com.circuloodontochaco.co.dao.PlanCuentaRepository;
import ar.com.circuloodontochaco.co.dao.queries.CodigoErogacionSpecifications;
import ar.com.circuloodontochaco.co.dao.search.CodigoErogacionSearch;
import ar.com.circuloodontochaco.co.model.CodigoErogacion;
import ar.com.circuloodontochaco.co.model.CodigoMovimiento;
import ar.com.circuloodontochaco.co.model.CodigoRetencionATP;
import ar.com.circuloodontochaco.co.model.contabilidad.PlanCuenta;

/**
 * @author Jorge E. Villaverde
 *
 */
@Controller
@SessionAttributes(types = CodigoErogacion.class)
public class CodigoErogacionController extends AdminProfileController<CodigoErogacion> {

	private static final String ENTITY_NAME = "codigoErogacion";
	
	// Dependencies -----------------------------------------------------------
	
    private PlanCuentaRepository planCuentaRepository;
    
    private CodigoRetencionATPRepository codigoRetencionATPRepository;
    
    private CodigoMovimientoRepository codigoMovimientoRepository;
    
    // Constructor ------------------------------------------------------------
    
    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }

    // Search -----------------------------------------------------------------
    
    @RequestMapping({"/admin/codigoErogacion/", "/admin/codigoErogacion"})
    public String rootSearch() {
    	return findRedirectPage();
    }
    
    @RequestMapping(value = "/admin/codigoErogacion/find.html", method = RequestMethod.GET)
    public String initFindForm(ModelMap model, @SortDefault("descripcion") Pageable pageable) {
    	
    	model.addAttribute("search", new CodigoErogacionSearch());
    	model.addAttribute("page", repository.findAll(pageable));

        return findPage();
    }    

    @RequestMapping(value = "/admin/codigoErogacion/find.html", method = RequestMethod.POST)
    public String processFindForm(
    		CodigoErogacionSearch search,  
    		BindingResult result, 
    		Model model, 
    		@SortDefault("descripcion") Pageable pageable) {

        Page<CodigoErogacion> results = this.repository.findAll(
        		CodigoErogacionSpecifications.fromSearch(search),
        		pageable);
        
        model.addAttribute("search", search);
        model.addAttribute("page", results);
        
        return findPage();
    }
    
    // Create -----------------------------------------------------------------
    
    @RequestMapping(value = "/admin/codigoErogacion/new", method = RequestMethod.GET)
    public String initCreationForm(Model model) {
    	CodigoErogacion entity = createEntity();

    	model.addAttribute(entityName(), entity);
        
        return formPage();
    }

    @RequestMapping(value = "/admin/codigoErogacion/new", method = RequestMethod.POST)
    public String processCreationForm(@Valid CodigoErogacion entity, BindingResult result, SessionStatus status) {
    	if (result.hasErrors()) {
        	return formPage();
        } else {
            this.repository.save(entity);
            status.setComplete();
            return redirectReadEntity(entity.getId());
        }
    }

    // Read -------------------------------------------------------------------
    
    @RequestMapping("/admin/codigoErogacion/{id}")
    public String initReadForm(@PathVariable("id") Long id, Model model) {    	
    	CodigoErogacion entity = repository.findOne(id);
    	
    	if(entity == null)
    		return findRedirectPage();
    	
        model.addAttribute(entityName(), entity);
        
        return detailPage();
    }
    
    // Update -----------------------------------------------------------------

    @RequestMapping(value = "/admin/codigoErogacion/{id}/edit", method = RequestMethod.GET)
    public String initUpdateForm(@PathVariable("id") Long id, Model model) {
    	CodigoErogacion entity = repository.findOne(id);

    	if(entity == null)
    		return findRedirectPage();
    	
        model.addAttribute(entityName(), entity);
        
        return editPage();
    }

    @RequestMapping(value = "/admin/codigoErogacion/{id}/edit", method = RequestMethod.POST)
    public String processUpdateForm(@Valid CodigoErogacion entity, 
    		BindingResult result, 
    		SessionStatus status) {
        if (result.hasErrors()) {
            return editPage();
        } else {
            this.repository.save(entity);
            status.setComplete();
            return redirectReadEntity(entity.getId());
        }
    }


    // Delete -----------------------------------------------------------------
    
    @RequestMapping(value = "/admin/codigoErogacion/{id}/del", method = RequestMethod.GET)
    public String initDeleteForm(@PathVariable("id") Long id, Model model) {
    	CodigoErogacion entity = repository.findOne(id);

    	if(entity == null)
    		return findRedirectPage();
    	
        model.addAttribute(entityName(), entity);
        
        return deletePage();
    }

    @RequestMapping(value = "/admin/codigoErogacion/{id}/del", method = RequestMethod.POST)
    public String processDeleteForm(@PathVariable("id") Long id, SessionStatus status) {
    	CodigoErogacion entity = repository.findOne(id);

    	if(entity != null) {
	    	this.repository.delete(entity);
	        status.setComplete();
    	}
    	
        return findRedirectPage();
    }
    
    // Model Attributes -------------------------------------------------------
    
    @ModelAttribute("allCuentasContables")
    public List<PlanCuenta> populateCuentasContables() {
        return planCuentaRepository.findAll();
    }

    @ModelAttribute("allCodigoRetencionATP")
    public List<CodigoRetencionATP> populateCodigoRetencionATP() {
        return codigoRetencionATPRepository.findAll();
    }
    
    @ModelAttribute("allCodigoMovimiento")
    public List<CodigoMovimiento> populateCodigoMovimiento() {
        return codigoMovimientoRepository.findAll(
        		new Sort(Sort.Direction.ASC, "descripcion"));
    }

    // Overrides --------------------------------------------------------------

	@Override
	public String entityName() {
		return ENTITY_NAME;
	}

	@Override
	protected CodigoErogacion createEntity() {
		return new CodigoErogacion();		
	}

	// Dependencies -----------------------------------------------------------
	
    @Autowired
    public void setCodigoRetencionATPRepository(
    		CodigoRetencionATPRepository codigoRetencionATPRepository) {
		this.codigoRetencionATPRepository = codigoRetencionATPRepository;
	}    

	@Autowired
	public void setCodigoMovimientoRepository(CodigoMovimientoRepository codigoMovimientoRepository) {
		this.codigoMovimientoRepository = codigoMovimientoRepository;
	}

	@Autowired
	public void setPlanCuentaRepository(PlanCuentaRepository planCuentaRepository) {
		this.planCuentaRepository = planCuentaRepository;
	}    
    
}
