package com.ejie.m62fb.control;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import com.ejie.m62fb.model.M62fbDisponibilidadVivs;
import com.ejie.m62fb.model.M62fbr44s0s00;
import com.ejie.m62fb.service.M62fbDisponibilidadVivsService;
import com.ejie.m62fb.service.M62fbSituacionVivService;
import com.ejie.m62fb.service.M62fbr44s0s00Service;
import com.ejie.x38.control.exception.ResourceNotFoundException;
import com.ejie.x38.control.exception.ServiceUnavailableException;
import com.ejie.x38.dto.JQGridJSONModel;
import com.ejie.x38.dto.Pagination;
import com.ejie.x38.util.ObjectConversionManager;

/**
 * M62fbr44s0s00Controller generated by UDA, 17-oct-2012 15:03:40.
 * 
XXXX
 */

@Controller
@RequestMapping(value = "catalogo/mantenimiento")
public class M62fbr44s0s00Controller {

	private static final Logger logger = LoggerFactory
			.getLogger(M62fbr44s0s00Controller.class);

	@Autowired
	private M62fbr44s0s00Service m62fbr44s0s00Service;
	@Autowired
	private M62fbDisponibilidadVivsService m62fbDisponibilidadVivsService;
	@Autowired
	private M62fbSituacionVivController m62fbSituacionVivController;
	@Autowired
	private M62fbSituacionVivService m62fbSituacionVivService;

	/**
	 * Method 'getCreateForm'.
	 * 
	 * @param model
	 *            Model
	 * @return String
	 */
	@RequestMapping(value = "maint", method = RequestMethod.GET)
	public String getCreateForm(Model model) {
		M62fbr44s0s00Controller.logger.info("[GET - View] : m62fbr44s0s00");
		model.addAttribute("comboCodSitCat",
				m62fbSituacionVivService.findAll(null, null));
		return "m62fbr44s0s00";
	}

	/**
	 * Method 'getById'.
	 * 
	 * @param idM62r44t0
	 *            Integer
	 * @param numVivienda
	 *            Integer
	 * @param fecIncorporacionCat
	 *            Date
	 * @param indDisponible
	 *            String
	 * @param codSituacion
	 *            String
	 * @param fecIniSituacion
	 *            Date
	 * @param fecFinSituacion
	 *            Date
	 * @param texObservaciones
	 *            String
	 * @param fehUltModif
	 *            Date
	 * @param codUsuUltModif
	 *            String
	 * @param ideRegistro
	 *            Integer
	 * @param fecAlta
	 *            Date
	 * @return m62fbr44s0s00 M62fbr44s0s00
	 */
	@RequestMapping(value = "/{numVivienda}", method = RequestMethod.GET)
	public @ResponseBody
	M62fbr44s0s00 getById(@PathVariable BigDecimal numVivienda) {
		M62fbr44s0s00 m62fbr44s0s00 = new M62fbr44s0s00();
		m62fbr44s0s00.setNumVivienda(numVivienda);
		m62fbr44s0s00 = this.m62fbr44s0s00Service.find(m62fbr44s0s00);
		M62fbr44s0s00Controller.logger
				.info("[GET - findBy_PK] : Obtener M62fbr44s0s00 por PK");
		return m62fbr44s0s00;
	}

	/**
	 * Method 'getAll'.
	 * 
	 * @param filterM62fbr44s0s00
	 *            M62fbr44s0s00
	 * @return List
	 */
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody
	List<M62fbr44s0s00> getAll(@ModelAttribute M62fbr44s0s00 filterM62fbr44s0s00) {
		M62fbr44s0s00Controller.logger
				.info("[GET - find_ALL] : Obtener M62fbr44s0s00 por filtro");
		return this.m62fbr44s0s00Service.findAll(filterM62fbr44s0s00, null);
	}

	/**
	 * Method 'edit'.
	 * 
	 * @param m62fbr44s0s00
	 *            M62fbr44s0s00
	 * @return M62fbr44s0s00
	 */
	@RequestMapping(method = RequestMethod.PUT)
	public @ResponseBody
	M62fbr44s0s00 edit(@RequestBody M62fbr44s0s00 m62fbr44s0s00) {
		M62fbr44s0s00 m62fbr44s0s00Aux = this.m62fbr44s0s00Service
				.update(m62fbr44s0s00);
		M62fbr44s0s00Controller.logger
				.info("[PUT] : M62fbr44s0s00 actualizado correctamente");
		return m62fbr44s0s00Aux;
	}

	/**
	 * Method 'add'.
	 * 
	 * @param m62fbr44s0s00
	 *            M62fbr44s0s00
	 * @return M62fbr44s0s00
	 */
	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody
	M62fbr44s0s00 add(@RequestBody M62fbr44s0s00 m62fbr44s0s00) {
		M62fbr44s0s00 m62fbr44s0s00Aux = this.m62fbr44s0s00Service
				.add(m62fbr44s0s00);
		M62fbr44s0s00Controller.logger
				.info("[POST] : M62fbr44s0s00 insertado correctamente");
		return m62fbr44s0s00Aux;
	}

	/**
	 * Method 'remove'.
	 * 
	 * @param idM62r44t0
	 *            Integer
	 * @param numVivienda
	 *            Integer
	 * @param fecIncorporacionCat
	 *            Date
	 * @param indDisponible
	 *            String
	 * @param codSituacion
	 *            String
	 * @param fecIniSituacion
	 *            Date
	 * @param fecFinSituacion
	 *            Date
	 * @param texObservaciones
	 *            String
	 * @param fehUltModif
	 *            Date
	 * @param codUsuUltModif
	 *            String
	 * @param ideRegistro
	 *            Integer
	 * @param fecAlta
	 *            Date
	 * @return m62fbr44s0s00
	 */
	@RequestMapping(value = "/{numVivienda}", method = RequestMethod.DELETE)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody
	M62fbr44s0s00 remove(@PathVariable BigDecimal numVivienda) {
		M62fbr44s0s00 m62fbr44s0s00 = new M62fbr44s0s00();
		m62fbr44s0s00.setNumVivienda(numVivienda);
		this.m62fbr44s0s00Service.remove(m62fbr44s0s00);
		M62fbr44s0s00Controller.logger
				.info("[DELETE] : M62fbr44s0s00 borrado correctamente");
		return m62fbr44s0s00;
	}

	/**
	 * Method 'removeAll'.
	 * 
	 * @param m62fbr44s0s00Ids
	 *            List
	 * @return m62fbr44s0s00List
	 */
	@RequestMapping(value = "/deleteAll", method = RequestMethod.POST)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody
	List<List<String>> removeMultiple(
			@RequestBody List<List<String>> m62fbr44s0s00Ids) {
		List<M62fbr44s0s00> m62fbr44s0s00List = new ArrayList<M62fbr44s0s00>();
		for (List<String> m62fbr44s0s00Id : m62fbr44s0s00Ids) {
			Iterator<String> iterator = m62fbr44s0s00Id.iterator();
			M62fbr44s0s00 m62fbr44s0s00 = new M62fbr44s0s00(); // NOPMD - Objeto
																// nuevo en la
																// lista
																// (parametro
																// del servicio)
			m62fbr44s0s00.setIdM62r44t0(ObjectConversionManager.convert(
					iterator.next(), BigDecimal.class));
			m62fbr44s0s00.setNumVivienda(ObjectConversionManager.convert(
					iterator.next(), BigDecimal.class));
			m62fbr44s0s00.setFecIncorporacionCat(ObjectConversionManager
					.convert(iterator.next(), java.util.Date.class));
			m62fbr44s0s00.setIndDisponible(ObjectConversionManager.convert(
					iterator.next(), String.class));
			m62fbr44s0s00.setCodSituacion(ObjectConversionManager.convert(
					iterator.next(), String.class));
			m62fbr44s0s00.setFecIniSituacion(ObjectConversionManager.convert(
					iterator.next(), java.util.Date.class));
			m62fbr44s0s00.setFecFinSituacion(ObjectConversionManager.convert(
					iterator.next(), java.util.Date.class));
			m62fbr44s0s00.setTexObservaciones(ObjectConversionManager.convert(
					iterator.next(), String.class));
			m62fbr44s0s00.setFehUltModif(ObjectConversionManager.convert(
					iterator.next(), java.util.Date.class));
			m62fbr44s0s00.setCodUsuUltModif(ObjectConversionManager.convert(
					iterator.next(), String.class));
			m62fbr44s0s00.setIdeRegistro(ObjectConversionManager.convert(
					iterator.next(), java.lang.Integer.class));
			m62fbr44s0s00.setFecAlta(ObjectConversionManager.convert(
					iterator.next(), java.util.Date.class));
			m62fbr44s0s00List.add(m62fbr44s0s00);
		}
		this.m62fbr44s0s00Service.removeMultiple(m62fbr44s0s00List);
		M62fbr44s0s00Controller.logger
				.info("[POST - DELETE_ALL] : M62fbr44s0s00 borrados correctamente");
		return m62fbr44s0s00Ids;
	}

	/**
	 * Method 'getAllJQGrid'.
	 * 
	 * @param filterM62fbr44s0s00
	 *            M62fbr44s0s00
	 * @param pagination
	 *            Pagination
	 * @return JQGridJSONModel
	 */
	@RequestMapping(method = RequestMethod.GET, headers = { "JQGridModel=true" })
	public @ResponseBody
	Object getAllJQGrid(
			@RequestParam(value = "numViviendaFiltro", required = false) BigDecimal numVivienda,
			@RequestParam(value = "numExpediente", required = false) String numExpediente,
			@RequestParam(value = "fecIncCatDesde", required = false) String fecIncCatDesde,
			@RequestParam(value = "fecIncCatHasta", required = false) String fecIncCatHasta,
			@RequestParam(value = "codProvinciaFiltro", required = false) String codProvincia,
			@RequestParam(value = "codMunicipioFiltro", required = false) String codMunicipio,
			@RequestParam(value = "codSitCatFiltro", required = false) String codSitCat,
			@RequestParam(value = "fecIniSitDesde", required = false) String fecIniSitDesde,
			@RequestParam(value = "fecIniSitHasta", required = false) String fecIniSitHasta,
			@RequestParam(value = "fecFinSitDesde", required = false) String fecFinSitDesde,
			@RequestParam(value = "fecFinSitHasta", required = false) String fecFinSitHasta,
			HttpServletRequest request) {
		try {
			Pagination pagination = null;

			if (request.getHeader("JQGridModel") != null
					&& request.getHeader("JQGridModel").equals("true")) {
				pagination = new Pagination();

				Long pagina = Long.valueOf(request.getParameter("page"));
				// pagina = Long.valueOf("975");
				pagination.setPage(pagina);

				pagination.setRows(Long.valueOf(request.getParameter("rows")));
				pagination.setSort(request.getParameter("sidx"));
				pagination.setAscDsc(request.getParameter("sord"));

				// Sustituir * por %
				if (numExpediente != null) {
					numExpediente = numExpediente.replaceAll("\\x2a", "%");
				}

				List<M62fbDisponibilidadVivs> catalogo = this.m62fbDisponibilidadVivsService
						.findAllPersonalizadoVivEnCatalogo(numVivienda,
								numExpediente, fecIncCatDesde, fecIncCatHasta,
								codProvincia, codMunicipio, codSitCat,
								fecIniSitDesde, fecIniSitHasta, fecFinSitDesde,
								fecFinSitHasta, pagination);

				if (catalogo == null) {
					throw new Exception("No data Found.");
				}

				Long total = getPorFiltroPersonalizadoVivEnCatalogoCount(
						numVivienda, numExpediente, fecIncCatDesde,
						fecIncCatHasta, codProvincia, codMunicipio, codSitCat,
						fecIniSitDesde, fecIniSitHasta, fecFinSitDesde,
						fecFinSitHasta, request);

				JQGridJSONModel data = new JQGridJSONModel();
				data.setPage(request.getParameter("page"));
				// data.setPage(pagina.toString());
				data.setRecords(total.intValue());
				data.setTotal(total, pagination.getRows());
				data.setRows(catalogo);
				return data;
			} else {
				List<M62fbDisponibilidadVivs> catalogo = this.m62fbDisponibilidadVivsService
						.findAllPersonalizadoVivEnCatalogo(numVivienda,
								numExpediente, fecIncCatDesde, fecIncCatHasta,
								codProvincia, codMunicipio, codSitCat,
								fecIniSitDesde, fecIniSitHasta, fecFinSitDesde,
								fecFinSitHasta, pagination);
				if (catalogo == null) {
					throw new Exception("No data Found.");
				}
				return catalogo;
			}
		} catch (Exception e) {
			throw new ResourceNotFoundException("No data Found.");
		}
	}

	/**
	 * Method 'getPorFiltroPersonalizadoVivEnCatalogoCount'.
	 * 
	 * @param idM62r45t0
	 *            Long
	 * @param request
	 *            HttpServletRequest
	 * @return Long
	 */
	@RequestMapping(value = "/filtrarCatalogoVivEnCatalogoCount", method = RequestMethod.GET)
	public @ResponseBody
	Long getPorFiltroPersonalizadoVivEnCatalogoCount(
			@RequestParam(value = "numVivienda", required = false) BigDecimal numVivienda,
			@RequestParam(value = "numExpediente", required = false) String numExpediente,
			@RequestParam(value = "fecIncCatDesde", required = false) String fecIncCatDesde,
			@RequestParam(value = "fecIncCatHasta", required = false) String fecIncCatHasta,
			@RequestParam(value = "codProvinciaFiltro", required = false) String codProvincia,
			@RequestParam(value = "codMunicipioFiltro", required = false) String codMunicipio,
			@RequestParam(value = "codSitCatFiltro", required = false) String codSitCat,
			@RequestParam(value = "fecIniSitDesde", required = false) String fecIniSitDesde,
			@RequestParam(value = "fecIniSitHasta", required = false) String fecIniSitHasta,
			@RequestParam(value = "fecFinSitDesde", required = false) String fecFinSitDesde,
			@RequestParam(value = "fecFinSitHasta", required = false) String fecFinSitHasta,
			HttpServletRequest request) {
		try {
			return m62fbDisponibilidadVivsService
					.findAllPersonalizadoVivEnCatalogoCount(numVivienda,
							numExpediente, fecIncCatDesde, fecIncCatHasta,
							codProvincia, codMunicipio, codSitCat,
							fecIniSitDesde, fecIniSitHasta, fecFinSitDesde,
							fecFinSitHasta);

		} catch (Exception e) {
			throw new ServiceUnavailableException(
					"Count Service is not responding.");
		}
	}

	@RequestMapping(value = "/catalogo_viviendas", method = RequestMethod.GET)
	public ModelAndView getCatalogoReport(
			Model model,
			@RequestParam(value = "numViviendaFiltro", required = false) BigDecimal numVivienda,
			@RequestParam(value = "numExpediente", required = false) String numExpediente,
			@RequestParam(value = "fecIncCatDesde", required = false) String fecIncCatDesde,
			@RequestParam(value = "fecIncCatHasta", required = false) String fecIncCatHasta,
			@RequestParam(value = "codProvinciaFiltro", required = false) String codProvincia,
			@RequestParam(value = "codMunicipioFiltro", required = false) String codMunicipio,
			@RequestParam(value = "codSitCatFiltro", required = false) String codSitCat,
			@RequestParam(value = "fecIniSitDesde", required = false) String fecIniSitDesde,
			@RequestParam(value = "fecIniSitHasta", required = false) String fecIniSitHasta,
			@RequestParam(value = "fecFinSitDesde", required = false) String fecFinSitDesde,
			@RequestParam(value = "fecFinSitHasta", required = false) String fecFinSitHasta,
			HttpServletRequest request, HttpServletResponse response)
			throws ParseException {
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		Pagination pagination = null;

		if (request.getHeader("JQGridModel") != null
				&& request.getHeader("JQGridModel").equals("true")) {
			pagination = new Pagination();
			pagination.setPage(Long.valueOf(request.getParameter("page")));
			pagination.setRows(Long.valueOf(request.getParameter("rows")));
			pagination.setSort(request.getParameter("sidx"));
			pagination.setAscDsc(request.getParameter("sord"));
		}
		List<M62fbDisponibilidadVivs> lista = null;

		lista = this.m62fbDisponibilidadVivsService
				.findAllPersonalizadoVivEnCatalogo(numVivienda, numExpediente,
						fecIncCatDesde, fecIncCatHasta, codProvincia,
						codMunicipio, codSitCat, fecIniSitDesde,
						fecIniSitHasta, fecFinSitDesde, fecFinSitHasta,
						pagination);

		model.addAttribute("excelCatalogo", lista);

		return new ModelAndView("excelCatalogo", "model", model);
	}

}
