package com.ejie.m62fb.control;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
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.M62fbRegAccesoService;
import com.ejie.m62fb.service.M62fbRegTenenciaService;
import com.ejie.m62fb.service.M62fbSituacionVivService;
import com.ejie.m62fb.service.M62fbr44s0s00Service;
import com.ejie.x38.control.exception.MethodFailureException;
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/agregaralcatalogo")
public class AgregarAlCatalogoController {

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

	@Autowired
	private M62fbr44s0s00Service m62fbr44s0s00Service;
	@Autowired
	private M62fbDisponibilidadVivsService m62fbDisponibilidadVivsService;
	@Autowired
	private M62fbSituacionVivService m62fbSituacionVivService;
	@Autowired
	private M62fbRegAccesoService m62fbRegAccesoService;
	@Autowired
	private M62fbRegTenenciaService m62fbRegTenenciaService;

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

		model.addAttribute("comboCodRegAcceso",
				m62fbRegAccesoService.findAll(null, null));

		model.addAttribute("comboCodRegTenencia",
				m62fbRegTenenciaService.findAll(null, null));
		return "agregaralcatalogo";
	}

	/**
	 * 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);
		AgregarAlCatalogoController.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) {
		AgregarAlCatalogoController.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);
		AgregarAlCatalogoController.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);
		AgregarAlCatalogoController.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);
		AgregarAlCatalogoController.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);
		AgregarAlCatalogoController.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 = "numExpedienteFiltro", required = false) String numExpediente,
			@RequestParam(value = "codProvinciaFiltro", required = false) String codProvincia,
			@RequestParam(value = "codMunicipioFiltro", required = false) String codMunicipio,
			@RequestParam(value = "codRegAccesoFiltro", required = false) String codRegAcceso,
			@RequestParam(value = "codRegTenenciaFiltro", required = false) String codRegTenencia,
			@RequestParam(value = "indVivAdaptadaFiltro", required = false) String indVivAdaptada,
			@RequestParam(value = "numDormitoriosDesde", required = false) Integer numDormitoriosDesde,
			@RequestParam(value = "numDormitoriosHasta", required = false) Integer numDormitoriosHasta,
			@RequestParam(value = "supUtilDesde", required = false) BigDecimal supUtilDesde,
			@RequestParam(value = "supUtilHasta", required = false) BigDecimal supUtilHasta,
			HttpServletRequest request) {
		try {
			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"));
				// Sustituir * por %
				if (numExpediente != null) {
					numExpediente = numExpediente.replaceAll("\\x2a", "%");
				}
				List<M62fbDisponibilidadVivs> catalogo = this.m62fbDisponibilidadVivsService
						.findAllListadoParaIncEnCatalogo(numVivienda,
								numExpediente, codProvincia, codMunicipio,
								codRegAcceso, codRegTenencia, indVivAdaptada,
								numDormitoriosDesde, numDormitoriosHasta,
								supUtilDesde, supUtilHasta, pagination);

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

				Long total = getListadoParaIncEnCatalogoCount(numVivienda,
						numExpediente, codProvincia, codMunicipio,
						codRegAcceso, codRegTenencia, indVivAdaptada,
						numDormitoriosDesde, numDormitoriosHasta, supUtilDesde,
						supUtilHasta, request);

				JQGridJSONModel data = new JQGridJSONModel();
				data.setPage(request.getParameter("page"));
				data.setRecords(total.intValue());
				data.setTotal(total, pagination.getRows());
				data.setRows(catalogo);
				return data;
			} else {
				// Sustituir * por %
				if (numExpediente != null) {
					numExpediente = numExpediente.replaceAll("\\x2a", "%");
				}
				List<M62fbDisponibilidadVivs> catalogo = this.m62fbDisponibilidadVivsService
						.findAllListadoParaIncEnCatalogo(numVivienda,
								numExpediente, codProvincia, codMunicipio,
								codRegAcceso, codRegTenencia, indVivAdaptada,
								numDormitoriosDesde, numDormitoriosHasta,
								supUtilDesde, supUtilHasta, 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 = "/ListadoParaIncEnCatalogoCount", method = RequestMethod.GET)
	public @ResponseBody
	Long getListadoParaIncEnCatalogoCount(
			@RequestParam(value = "numViviendaFiltro", required = false) BigDecimal numVivienda,
			@RequestParam(value = "numExpedienteFiltro", required = false) String numExpediente,
			@RequestParam(value = "codProvinciaFiltro", required = false) String codProvincia,
			@RequestParam(value = "codMunicipioFiltro", required = false) String codMunicipio,
			@RequestParam(value = "codRegAccesoFiltro", required = false) String codRegAcceso,
			@RequestParam(value = "codRegTenenciaFiltro", required = false) String codRegTenencia,
			@RequestParam(value = "indVivAdaptadaFiltro", required = false) String indVivAdaptada,
			@RequestParam(value = "numDormitoriosDesde", required = false) Integer numDormitoriosDesde,
			@RequestParam(value = "numDormitoriosHasta", required = false) Integer numDormitoriosHasta,
			@RequestParam(value = "supUtilDesde", required = false) BigDecimal supUtilDesde,
			@RequestParam(value = "supUtilHasta", required = false) BigDecimal supUtilHasta,
			HttpServletRequest request) {
		try {
			// Sustituir * por %
			if (numExpediente != null) {
				numExpediente = numExpediente.replaceAll("\\x2a", "%");
			}
			return m62fbDisponibilidadVivsService
					.findAllListadoParaIncEnCatalogoCount(numVivienda,
							numExpediente, codProvincia, codMunicipio,
							codRegAcceso, codRegTenencia, indVivAdaptada,
							numDormitoriosDesde, numDormitoriosHasta,
							supUtilDesde, supUtilHasta);

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

	/**
	 * Method 'addvivMasivasOfer'.
	 * 
	 * @param idM62r45t0
	 *            BigDecimal
	 * @param viviendasIds
	 *            ArrayList
	 * @param response
	 *            HttpServletResponse
	 */
	@RequestMapping(value = "/addIncMasivaViv", method = RequestMethod.POST)
	public @ResponseBody
	M62fbr44s0s00 addvivMasivasOfer(
			@RequestParam(value = "codSituacion", required = false) String codSituacion,
			@RequestParam(value = "fecIniSituacion", required = false) Date fecIniSituacion,
			@RequestParam(value = "fecFinSituacion", required = false) Date fecFinSituacion,
			@RequestParam(value = "texObservaciones", required = false) String texObservaciones,
			@RequestParam(value = "viviendasIds", required = false) ArrayList<String> viviendasIds,
			HttpServletResponse response) {
		try {
			ArrayList<M62fbr44s0s00> viviendasList = new ArrayList<M62fbr44s0s00>();
			for (String viviendasId : viviendasIds) {

				M62fbr44s0s00 viviendas = new M62fbr44s0s00();
				viviendas.setNumVivienda(ObjectConversionManager.convert(
						viviendasId, java.math.BigDecimal.class));
				viviendas.setFecIniSituacion(fecIniSituacion);
				viviendas.setCodSituacion(codSituacion);
				viviendas.setFecFinSituacion(fecFinSituacion);
				viviendas.setTexObservaciones(texObservaciones);
				viviendasList.add(viviendas);
			}
			this.m62fbr44s0s00Service.addIncMasivaViv(viviendasList);
			response.setStatus(HttpServletResponse.SC_OK);
			return new M62fbr44s0s00();
		} catch (Exception e) {
			throw new MethodFailureException("Method failed");
		}
	}

	/**
	 * Method 'addvivMasivasOfer'.
	 * 
	 * @param idM62r45t0
	 *            BigDecimal
	 * @param viviendasIds
	 *            ArrayList
	 * @param response
	 *            HttpServletResponse
	 */
	@RequestMapping(value = "/valViviendasSel", method = RequestMethod.GET)
	public @ResponseBody
	Long valViviendasSel(
			@RequestParam(value = "viviendasIds", required = false) ArrayList<String> viviendasIds,
			HttpServletRequest request) {
		try {
			Long resultado;
			String listadoVivs = "";
			for (String viviendasId : viviendasIds) {
				if (listadoVivs == "") {
					listadoVivs = "" + viviendasId;
				} else {
					listadoVivs = listadoVivs.concat(",").concat(viviendasId);
				}
			}
			resultado = this.m62fbr44s0s00Service.valViviendasSel(listadoVivs);
			return resultado;
		} catch (Exception e) {
			throw new ServiceUnavailableException(
					"Count Service is not responding.");
		}
	}

	@RequestMapping(value = "/registroExcel", method = RequestMethod.GET)
	public ModelAndView getCatalogoReport(
			Model model,
			@RequestParam(value = "numViviendaFiltro", required = false) BigDecimal numVivienda,
			@RequestParam(value = "numExpedienteFiltro", required = false) String numExpediente,
			@RequestParam(value = "codProvinciaFiltro", required = false) String codProvincia,
			@RequestParam(value = "codMunicipioFiltro", required = false) String codMunicipio,
			@RequestParam(value = "codRegAccesoFiltro", required = false) String codRegAcceso,
			@RequestParam(value = "codRegTenenciaFiltro", required = false) String codRegTenencia,
			@RequestParam(value = "indVivAdaptadaFiltro", required = false) String indVivAdaptada,
			@RequestParam(value = "numDormitoriosDesde", required = false) Integer numDormitoriosDesde,
			@RequestParam(value = "numDormitoriosHasta", required = false) Integer numDormitoriosHasta,
			@RequestParam(value = "supUtilDesde", required = false) BigDecimal supUtilDesde,
			@RequestParam(value = "supUtilHasta", required = false) BigDecimal supUtilHasta,
			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
				.findAllListadoParaIncEnCatalogo(numVivienda, numExpediente,
						codProvincia, codMunicipio, codRegAcceso,
						codRegTenencia, indVivAdaptada, numDormitoriosDesde,
						numDormitoriosHasta, supUtilDesde, supUtilHasta,
						pagination);

		model.addAttribute("excelRegistro", lista);

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

}
