/**
 * 
 */
package com.ejie.y42b.control;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ejie.x38.control.exception.ResourceNotFoundException;
import com.ejie.x38.dto.JQGridJSONModel;
import com.ejie.x38.dto.Pagination;
import com.ejie.y42b.constantes.Y42bAgendaConstantes;
import com.ejie.y42b.model.T17Calle;
import com.ejie.y42b.model.T17Localidad;
import com.ejie.y42b.model.T17Municipio;
import com.ejie.y42b.model.T17Pais;
import com.ejie.y42b.model.T17Portal;
import com.ejie.y42b.model.T17Provincia;
import com.ejie.y42b.model.T17TipoVia;
import com.ejie.y42b.service.T17CalleService;
import com.ejie.y42b.service.T17LocalidadService;
import com.ejie.y42b.service.T17MunicipioService;
import com.ejie.y42b.service.T17PaisService;
import com.ejie.y42b.service.T17PortalService;
import com.ejie.y42b.service.T17ProvinciaService;
import com.ejie.y42b.service.T17TipoViaService;

/**
 *  
 * 
 */
@Controller()
@RequestMapping(value = "/nora")
public class Y42bLoadGeoComponent {

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

	@Autowired()
	private Properties appConfiguration;

	@Autowired()
	private T17PaisService paisService;

	@Autowired()
	private T17ProvinciaService provinciaService;

	@Autowired()
	private T17MunicipioService municipioService;

	@Autowired()
	private T17LocalidadService localidadService;

	@Autowired()
	private T17CalleService calleService;

	@Autowired()
	private T17PortalService portalService;
	
	@Autowired()
	private T17TipoViaService tipoViaService;

	/**
	 * Method 'getCreateForm'.
	 * 
	 * @param model
	 *            Model
	 * @return String
	 */
	@RequestMapping(value = "maintBusquedaCalle", method = RequestMethod.GET)
	public ModelAndView getCreateFormBusquedaCalle(Model model) {
		model.addAttribute("defaultLanguage",
				appConfiguration.get("y42bVistaWar.default.language"));
		model.addAttribute("defaultLayout",
				appConfiguration.get("y42bVistaWar.default.layout"));
		return new ModelAndView("busquedaCalle", "model", model);
	}

	
	
	
	
	/********************************************************************************
	 * Provincias NOCAPV
	 *******************************************************************************/
	/**
	 * Method 'getProvinciabyId'.
	 * 
	 * @param idProvincia
	 *            identificador de la provincia
	 * 
	 * @return 'provincia'
	 */
	
	@RequestMapping(value = "/provinciaById/{idProvincia}", method = RequestMethod.GET)
	public @ResponseBody()
	T17Provincia getProvinciaById(@PathVariable String idProvincia){
		T17Provincia t17provincia = new T17Provincia();
		t17provincia.setId(idProvincia);
		Y42bLoadGeoComponent.logger.debug("Cargar provincia");
		return this.provinciaService.find(t17provincia);
	}
	
	/********************************************************************************
	 * 
	 * COMBO
	 * 
	 *******************************************************************************/
		
	/********************************************************************************
	 * Provincias NOCAPV
	 *******************************************************************************/
	/**
	 * Method 'getProvincias'.NOCAPV
	 * 
	 * @return 'lista de provincias' para el COMBO
	 */
	@RequestMapping(value = "/provinciasResto", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Provincia> getRestoProvincias() {
		T17Provincia t17provincia = new T17Provincia();
		t17provincia.setAutonomiaId(Y42bAgendaConstantes.CAPV);
		Y42bLoadGeoComponent.logger.debug("Cargar provincias");
		return this.provinciaService.findAllResto(t17provincia, null);
	}
	
	
	
	/********************************************************************************
	 * Provincias CAPV
	 *******************************************************************************/
	/**
	 * Method 'getProvincias'. SOLO CAPV
	 * 
	 * @return 'lista de provincias' para el COMBO
	 */
	@RequestMapping(value = "/provincias", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Provincia> getProvincias() {
		T17Provincia t17provincia = new T17Provincia();
		t17provincia.setAutonomiaId(Y42bAgendaConstantes.CAPV);
		Y42bLoadGeoComponent.logger.debug("Cargar provincias");
		return this.provinciaService.findAll(t17provincia, null);
	}

	/**
	 * Method 'getProvincias'. SOLO CAPV
	 * 
	 * @return 'lista de provincias' para el COMBO
	 */
	@RequestMapping(value = "/provinciasTodas", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Provincia> getProvinciasTodas() {
		T17Provincia t17provincia = new T17Provincia();
		//t17provincia.setAutonomiaId(Y42bAgendaConstantes.CAPV);
		Y42bLoadGeoComponent.logger.debug("Cargar provincias");
		return this.provinciaService.findAll(t17provincia, null);
	}

	/********************************************************************************
	 * Municipios
	 *******************************************************************************/
	/**
	 * Method 'getMunicipios'.
	 * 
	 * @param provinciaId
	 *            identificador de la provincia
	 * @return 'lista de municipio' para el COMBO
	 */
	@RequestMapping(value = "/municipios", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Municipio> getMunicipios(@RequestParam(value = "provinciaId", required = false) String provinciaId) {

	    	T17Municipio t17Municipio = new T17Municipio();
		t17Municipio.setProvinciaId(provinciaId);
		return this.municipioService.findAll(t17Municipio, null);
		
	}

	/********************************************************************************
	 * Localidades
	 *******************************************************************************/
	/**
	 * Method 'getLocalidades'.
	 * 
	 * @param provinciaId
	 *            identificador de la provincia
	 * @param municipalityId
	 *            identificador de la provincia
	 * @return 'lista de municipio' para el COMBO
	 */
	@RequestMapping(value = "/localidades", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Localidad> getLocalidades(@RequestParam(value = "provinciaId", required = false) String provinciaId, @RequestParam(value = "municipioId", required = false) String municipalityId) {

		T17Localidad t17Localidad = new T17Localidad();
		t17Localidad.setProvinciaId(provinciaId);
		t17Localidad.setMunicipioId(municipalityId);
		return this.localidadService.findAll(t17Localidad, null);

	}

	/********************************************************************************
	 * Calles
	 *******************************************************************************/
	/**
	 * Method 'getCalles'.
	 * 
	 * @param provinciaId
	 *            identificador de la provincia
	 * @param municipalityId
	 *            identificador de la provincia
	 *            
	 * @return 'lista de municipio' para el COMBO
	 */
	@RequestMapping(value = "/calles", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Calle> getCalles(@RequestParam(value = "provinciaId", required = false) String provinciaId, @RequestParam(value = "municipioId", required = false) String municipalityId) {

		T17Calle t17Calle = new T17Calle();
		t17Calle.setProvinciaId(provinciaId);
		t17Calle.setMunicipioId(municipalityId);
		
		List<T17Calle> listCalles = new ArrayList<T17Calle>();
		
		listCalles =  this.calleService.findAll(t17Calle, null);
		
		return listCalles;

	}

	/********************************************************************************
	 * Paises
	 *******************************************************************************/
	/**
	 * Method 'getPaises'.
	 * 
	 * @return 'lista de paises' para el COMBO
	 */
	@RequestMapping(value = "paises", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Pais> getPaises() {
		Y42bLoadGeoComponent.logger.debug("Cargar paises");
		T17Pais pais = new T17Pais();
		// pais.setId("351");
		return this.paisService.findAll(pais, null);

	}
	
	/**
	 * Method 'getPaisesExtranjeros' Recupera la lista de paises sin españa
	 * 
	 * @return 'lista de paises' para el COMBO
	 */
	@RequestMapping(value = "paisesExtranjeros", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Pais> getPaisesExtranjeros() {
		Y42bLoadGeoComponent.logger.debug("Cargar paises");
		T17Pais pais = new T17Pais();
		pais.setId("108");
		return this.paisService.findAllExtranjeros(pais, null);

	}
		
	
	/********************************************************************************
	 * Portal
	 *******************************************************************************/
	/**
	 * Method 'getPortales'.
	 * 
	 * @param localidadId
	 *            identificador de la localidad
	 * @param calleId
	 *            identificador de la calle
	 * @return 'lista de municipio' para el COMBO
	 */
	@RequestMapping(value = "/portales", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Portal> getPortales(
			@RequestParam(value = "localidadId", required = false) String localidadId,
			@RequestParam(value = "calleId", required = false) Long calleId) {

		if ( //localidad no obligatoria
//				localidadId != null 
//				&& !localidadId.equals("")
//				&& !localidadId.equals("null") 
//				&& 
				calleId != null
				&& calleId != 0) {
			T17Portal t17Portal = new T17Portal();
//			t17Portal.setLocalidadId(localidadId);
			t17Portal.setCalleId(calleId);

			List<T17Portal> listPortales = new ArrayList<T17Portal>();
			listPortales =  this.portalService.findAll(t17Portal, null);
			
			return listPortales;
			
		} else {
			return (List<T17Portal>) new ArrayList<T17Portal>();
		}
	}
	
	/********************************************************************************
	 * CP
	 *******************************************************************************/
	/**
	 * Method 'getCP'.
	 * 
	 * @param q parametro de entrada
	 * @param c parametro de entrada
	 * @return List<T17Portal>
	 */
	@RequestMapping(value = "/cp", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17Portal> getCP(@RequestParam(value = "q", required = true) String q, @RequestParam(value = "c", required = true) Boolean c) {

		// HashMap<String, String> aMap = null;
		// List<HashMap<String, String>> lst = new ArrayList<HashMap<String,
		// String>>();

		// aMap = new HashMap<String, String>();
		// aMap.put("label", "48940");
		// aMap.put("value", "48940");
		// lst.add(aMap);

		// aMap = new HashMap<String, String>();
		// aMap.put("label", "48003");
		// aMap.put("value", "48003");
		// lst.add(aMap);
		
		T17Portal t17Portal = new T17Portal();
		t17Portal.setCodigoPostal(q);
		// }
		List<T17Portal> ls = null;
		try {
			ls = this.portalService.findAllLikeCodigoPostal(t17Portal, null, false);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ls;

	}
	
	
	/********************************************************************************
	 * Codigo Postal
	 *******************************************************************************/
	/**
	 * Method 'getCodigoPostal'.
	 * 
	 * @param portal
	 *            identificador del portal
	 * @return 'lista de municipio' para el COMBO
	 */
	@RequestMapping(value = "/codigo_postal/{portal}", method = RequestMethod.GET)
	public @ResponseBody()
	T17Portal getCodigoPostal(@PathVariable() String portal) {
		try
		{
			T17Portal t17Portal = new T17Portal();
			t17Portal.setId(new Long(portal));
			
	/*		T17Portal t17PortalNew = new T17Portal();
			t17PortalNew = this.portalService.findCodigoPostal(t17Portal);
			
			return t17PortalNew;*/
			return this.portalService.findCodigoPostal(t17Portal);
		
		} catch (Exception e) {
			throw new ResourceNotFoundException("No data Found.");
		}
	}
	
	
	/**
	 * Method 'getProvMun'. Recupera la provincia y el municipio a partir de un
	 * cod postal
	 * 
	 * @param codigoPostal
	 *            identificador del codigo postal
	 * @return T17Portal
	 */
	@RequestMapping(value = "/codigo_postal/obtenerprovmun/{codigoPostal}", method = RequestMethod.GET)
	public @ResponseBody()
	T17Calle getProvMun(@PathVariable() String codigoPostal) {

		T17Portal t17Portal = new T17Portal();
		t17Portal.setCodigoPostal(codigoPostal);
		return this.calleService.findProvMun(t17Portal);

	}
	

	/**
	 * Method 'getAppConfiguration'.
	 * 
	 * @return appConfiguration
	 * 
	 */
	public Properties getAppConfiguration() {
		return this.appConfiguration;
	}

	/**
	 * Method 'setAppConfiguration'.
	 * 
	 * @param appConfiguration Properties
	 * 
	 */
	public void setAppConfiguration(Properties appConfiguration) {
		this.appConfiguration = appConfiguration;
	}
	
	

	/********************************************************************************
	 * Tipos via
	 *******************************************************************************/
	/**
	 * Method 'getAllTipoVia'.
	 * 
	 * @return 'lista de tipos de via' para el COMBO
	 */
	@RequestMapping(value = "/tipoVia", method = RequestMethod.GET)
	public @ResponseBody()
	List<T17TipoVia> getAllTipoVia() {

		return this.tipoViaService.findAll(null, null);
	}
	
	
	/********************************************************************************
	 * Busqueda Calles
	 *******************************************************************************/
	/**
	 * Method 'getCallesLike'.
	 * 
	 * 
	 * @param dsO_
	 *            descripcion calle
	 * @param tipoViaId_
	 *            identificador del tipo de via
	 * @param provinciaId
	 *            identificador de la provincia
	 * @param municipalityId
	 *            identificador del municipio
	 * @param request
	 *            HttpServletRequest
	 * @return 'lista de municipio' para el COMBO
	 */
	@RequestMapping(value = "/busquedaCalles", method = RequestMethod.GET)
	public @ResponseBody()
	Object getCallesLike(
			@RequestParam(value = "dsO", required = false) String dsO_,
			@RequestParam(value = "tipoViaId", required = false) String tipoViaId_,
			@RequestParam(value = "provinciaId", required = false) String provinciaId,
			@RequestParam(value = "municipioId", required = false) String municipalityId,
			HttpServletRequest request) {
		try {
			// control de los campos susceptibles de llegar a "" desde el filtro
			String tipoViaId = ("".equals(tipoViaId_)) ? null : tipoViaId_;
			String dsO = ("".equals(dsO_)) ? null : dsO_;

			T17Calle t17Calle = new T17Calle();
			t17Calle.setProvinciaId(provinciaId);
			t17Calle.setMunicipioId(municipalityId);
			t17Calle.setTipoViaId(tipoViaId);
			t17Calle.setDsO(dsO);

			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<T17Calle> callesBusqueda = this.calleService
						.findAllCalleLike(t17Calle, pagination, false);

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

				Long total = this.calleService.findAllCalleLikeCount(t17Calle,
						false);

				JQGridJSONModel data = new JQGridJSONModel();
				data.setPage(request.getParameter("page"));
				data.setRecords(total.intValue());
				data.setTotal(total, pagination.getRows());
				data.setRows(callesBusqueda);
				return data;
			} else {

				List<T17Calle> callesBusqueda = this.calleService
						.findAllCalleLike(t17Calle, pagination, false);

				if (callesBusqueda == null) {
					throw new Exception("No data Found.");
				}
				return callesBusqueda;
			}
		} catch (Exception e) {
			throw new ResourceNotFoundException("No data Found.");
		}
	}
}


