package com.ejie.aa20b.control;

import com.ejie.aa20b.service.Aa20bProcesosJMSService;
import com.ejie.aa20b.service.GamasService;
import com.ejie.aa20b.util.Aa20bConstantes;
import com.ejie.x38.dto.JQGridJSONModel;
import com.ejie.x38.dto.Pagination;
import com.ejie.x38.util.ObjectConversionManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
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 com.ejie.aa20b.classes.Aa20bFecha;
import com.ejie.aa20b.model.Gamas;

/**
 * GamasController generated by UDA, 02-mar-2015 11:32:38.
 * 
 * @author UDA
 */

@Controller
@RequestMapping(value = "/gamas")
public class GamasController {

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

	@Autowired
	private PropertiesFactoryBean appConfiguration;

	@Autowired
	private GamasService gamasService;

	@Autowired
	private Aa20bProcesosJMSService procesosJMSService;

	/**
	 * Method 'getCreateForm'.
	 * 
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 */
	@RequestMapping(value = "maint", method = RequestMethod.GET)
	public String getCreateForm(Model model, HttpServletRequest request) {
		GamasController.logger.info("[GET - View] : gamas");
		// Borrar el filtro de la sesion
		request.getSession().removeAttribute("FiltroGamas");

		return "gamas";
	}

	/**
	 * Method 'maintVolver'.
	 * 
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 */
	@RequestMapping(value = "maintVolver", method = RequestMethod.GET)
	public String maintVolver(Model model, HttpServletRequest request) {
		GamasController.logger.info("[GET - View] : gamas");
		// Meter en sesion el filtro para si edita un parte al volver cargar el
		// filtro
		Gamas gamaFiltro = (Gamas) request.getSession().getAttribute(
				"FiltroGamas");

		model.addAttribute("FiltroGama", gamaFiltro);

		return "gamas";
	}

	/**
	 * Method 'getById'.
	 * 
	 * @param idgama
	 *            Long
	 * @return gamas Gamas
	 */
	@RequestMapping(value = "/{idgama}", method = RequestMethod.GET)
	public @ResponseBody
	Gamas getById(@PathVariable Long idgama) {
		Gamas gamas = new Gamas();
		gamas.setIdgama(idgama);
		gamas = this.gamasService.find(gamas);
		GamasController.logger.info("[GET - findBy_PK] : Obtener Gamas por PK");
		return gamas;
	}

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

	/**
	 * Method 'edit'.
	 * 
	 * @param gamas
	 *            Gamas
	 * @return Gamas
	 */
	@RequestMapping(method = RequestMethod.PUT)
	public @ResponseBody
	Gamas edit(@RequestBody Gamas gamas) {
		Gamas gamasAux = this.gamasService.update(gamas);
		GamasController.logger.info("[PUT] : Gamas actualizado correctamente");
		return gamasAux;
	}

	/**
	 * Method 'add'.
	 * 
	 * @param gamas
	 *            Gamas
	 * @return Gamas
	 */
	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody
	Gamas add(@RequestBody Gamas gamas) {
		Gamas gamasAux = this.gamasService.add(gamas);
		GamasController.logger.info("[POST] : Gamas insertado correctamente");
		return gamasAux;
	}

	/**
	 * Method 'remove'.
	 * 
	 * @param idgama
	 *            Long
	 * @return gamas
	 */
	@RequestMapping(value = "/{idgama}", method = RequestMethod.DELETE)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody
	Gamas remove(@PathVariable Long idgama) {
		Gamas gamas = new Gamas();
		gamas.setIdgama(idgama);
		this.gamasService.remove(gamas);
		GamasController.logger.info("[DELETE] : Gamas borrado correctamente");
		return gamas;
	}

	/**
	 * Method 'removeAll'.
	 * 
	 * @param gamasIds
	 *            List
	 * @return gamasList
	 */
	@RequestMapping(value = "/deleteAll", method = RequestMethod.POST)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody
	List<List<String>> removeMultiple(@RequestBody List<List<String>> gamasIds) {
		List<Gamas> gamasList = new ArrayList<Gamas>();
		for (List<String> gamasId : gamasIds) {
			Iterator<String> iterator = gamasId.iterator();
			Gamas gamas = new Gamas(); // NOPMD - Objeto nuevo en la lista
										// (parametro del servicio)
			gamas.setIdgama(ObjectConversionManager.convert(iterator.next(),
					Long.class));
			gamasList.add(gamas);
		}
		this.gamasService.removeMultiple(gamasList);
		GamasController.logger
				.info("[POST - DELETE_ALL] : Gamas borrados correctamente");
		return gamasIds;
	}

	/**
	 * Method 'getAllJQGrid'.
	 * 
	 * @param filterGamas
	 *            Gamas
	 * @param pagination
	 *            Pagination
	 * @param locale
	 *            Locale
	 * @param request
	 *            HttpServletRequest
	 * @return JQGridJSONModel
	 */
	@RequestMapping(method = RequestMethod.GET, headers = { "JQGridModel=true" })
	public @ResponseBody
	JQGridJSONModel getAllJQGrid(@ModelAttribute Gamas filterGamas,
			Locale locale, @ModelAttribute Pagination pagination,
			HttpServletRequest request) {
		List<Gamas> gamass = this.gamasService.findAllLike(filterGamas,
				pagination, false);
		Long recordNum = this.gamasService.findAllLikeCount(filterGamas, false);
		GamasController.logger.info("[GET - jqGrid] : Obtener Gamas");

		// Meter en sesion el filtro para si edita un parte al volver cargar el
		// filtro
		if (filterGamas.getFeini() != null) {
			try {
				filterGamas.setStrFeini(Aa20bFecha.getFechaFormateada(
						filterGamas.getFeini(), locale));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		request.getSession().setAttribute("FiltroGamas", filterGamas);
		return new JQGridJSONModel(pagination, recordNum, gamass);
	}

	/**
	 * 
	 * @param model
	 *            Model
	 * @return String
	 */
	@RequestMapping(value = "/modificar", method = RequestMethod.GET)
	public String getCreateFormModficar(Model model, HttpServletRequest request) {
		GamasController.logger.info("[GET - View] : modificar gama");

		Long idGama = Long.parseLong(request.getParameter("idGama"));

		GamasController.logger.info("[GET - View] : modificar Gama : gama: "
				+ idGama);

		Gamas gama = this.getById(idGama);

		GamasController.logger.info("[GET - View] : modificar gama : "
				+ gama.toString());

		model.addAttribute("Gama", gama);

		request.setAttribute("accion", Aa20bConstantes.ACCION_MODIFICAR);
		return "editarGama";
	}

	/**
	 * Method 'edit'.
	 * 
	 * @param gama
	 *            Gamas
	 * @return Gamas
	 */
	@RequestMapping(value = "/modificarGama", method = RequestMethod.POST)
	public @ResponseBody
	Gamas modificarGama(@RequestBody Gamas gama) {

		GamasController.logger.info("[POST] : MODIFY : Valor de Baja : "
				+ gama.getBaja());

		/**
		 * GMAO Comprobaremos si el espacio no se encontraba de baja. Relleno
		 */
		boolean sincronizarTodasGamasGmao = false;
		boolean sincronizarGamaGmao = true;
		Gamas gamaBaja = this.getById(gama.getIdgama());
		/***/

		if (gama.getBaja() == null) {
			/**
			 * GMAO Si estaba de baja significa que se ha puesto de alta ahora y
			 * hay que sincronizar con Gmao
			 */
			if (gamaBaja.getBaja() != null && gamaBaja.getBaja().equals("1")) {
				sincronizarTodasGamasGmao = true;
			}

			gama.setBaja("0");
		} else {

			/**
			 * GMAO Si no estaba de baja significa que se ha puesto de baja
			 * ahora y hay que sincronizar con Gmao
			 */
			if (gamaBaja.getBaja() == null
					|| (gamaBaja.getBaja() != null && gamaBaja.getBaja()
							.equals("0"))) {
				sincronizarTodasGamasGmao = true;
			} else {
				// Si estaba de baja y sigue de baja no actualizamos GMAO
				sincronizarGamaGmao = false;
			}
			/***/

			gama.setBaja("1");
		}

		GamasController.logger.info("[PUT] : Gama antes de modificar : "
				+ gama.toString());
		Gamas gamaAux = this.gamasService.update(gama);
		GamasController.logger.info("[PUT] : Gama actualizado correctamente");

		/**
		 * GMAO - Si la actualización de la gama ha ido bien, generamos un
		 * mensaje en la cola para actualizar la entidad 'gama' en BBDD
		 * movilgmao. Si se ha puesto de baja, se deben sincronizar todas las
		 * entidades 'estancia'
		 */
		if (sincronizarTodasGamasGmao) {
			Gamas gamaFilter = new Gamas();
			gamaFilter.setBaja("0");
			List<Gamas> gamas = this.gamasService.findAll(gamaFilter, null);

			/**
			 * GMAO Sincronizacion de todos los codigos
			 */
			String urlConfig = "";
			try {
				urlConfig = this.appConfiguration.getObject().getProperty(
						"movilgmao.path");
			} catch (Exception e) {

			}
			this.procesosJMSService.sincronizarTodosGamasGmao(gamas,
					Aa20bConstantes.COLA, urlConfig);
		} else {

			if (sincronizarGamaGmao) {
				GamasController.logger
						.info("[JMS] notificar modificación gama movilgmao");

				this.procesosJMSService.sincronizarGamaGmao(gama);
			}

		}

		return gamaAux;

	}

	@RequestMapping(value = "/addNuevaGama", method = RequestMethod.POST)
	public @ResponseBody
	Gamas addNuevaGama(@RequestBody Gamas gama, Model model) {

		GamasController.logger.info("[POST] : ENTRAMOS EN ADD gama");

		GamasController.logger.info("[POST] : ADD : gama : " + gama.toString());
		gama.setBaja("0");
		if (gama.getSemanas() == null) {
			gama.setSemanas((long) 0);
		}
		Gamas gamaAux = this.gamasService.add(gama);
		GamasController.logger.info("[POST] : gama insertado correctamente");

		/**
		 * GMAO Sincronizacion de todos las gamas
		 */

		GamasController.logger
				.info("[JMS] notificar modificación gama movilgmao");

		this.procesosJMSService.sincronizarGamaGmao(gama);

		return gamaAux;
	}

	/**
	 * Method 'getCreateForm2'.
	 * 
	 * @param model
	 *            Model
	 * @return String
	 */
	@RequestMapping(value = "nuevo", method = RequestMethod.GET)
	public String getCreateForm2(Model model, HttpServletRequest request) {
		GamasController.logger.info("[GET - View] : nueva gama");
		model.addAttribute("accion", Aa20bConstantes.ACCION_NUEVO);

		request.getSession(true).setAttribute("accion",
				Aa20bConstantes.ACCION_NUEVO);
		return "editarGama";
	}

	/**
	 * Method 'nuevoGama'.
	 * 
	 * @param model
	 *            Model
	 * @return String
	 */
	@RequestMapping(value = "/nuevoGama", method = RequestMethod.GET)
	public String nuevoGama(Model model) {

		GamasController.logger.info("[GET - View] : nuevo gama");
		return "nuevoGama";
	}

	/**
	 * Method 'getById'.
	 * 
	 * @param idGamaBusc
	 *            String
	 * @param ventanaOrigen
	 *            String
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return editarGama String
	 */
	@RequestMapping(value = "/buscarGama", method = RequestMethod.POST)
	public String getById(@RequestParam String idGamaBusc,
			@RequestParam String ventanaOrigen, Model model,
			HttpServletRequest request) {

		GamasController.logger.info("[GET - findBy_PK] : Gama");

		Gamas gama = new Gamas();

		gama = this.gamasService.obtenerGama(idGamaBusc);

		GamasController.logger.info("[GET - findBy_PK] : Gama: "
				+ gama.toString());

		model.addAttribute("Gama", gama);
		model.addAttribute("accion", Aa20bConstantes.ACCION_MODIFICAR);

		// Meto en sesión la ventana origen
		request.getSession().setAttribute("ventanaOrigen", ventanaOrigen);
		model.addAttribute("ventanaOrigen", ventanaOrigen);

		return "editarGama";
	}

	/**
	 * Method 'add'.
	 * 
	 * @param gamas
	 *            Gamas
	 * @return Gamas
	 */
	@RequestMapping(value = "/alta", method = RequestMethod.POST)
	public @ResponseBody
	Gamas alta(@RequestBody Gamas gamas) {

		Date fechaHoy = new Date();
		gamas.setFeini(fechaHoy);
		gamas.setBaja("0");
		if (gamas.getSemanas() == null) {
			gamas.setSemanas((long) 0);
		}
		Gamas gamasAux = this.gamasService.add(gamas);
		GamasController.logger.info("[POST] : Gamas insertado correctamente");
		return gamasAux;
	}

	/**
	 * Method 'obtenerGamasAlta'.
	 * 
	 * @param filterGamas
	 *            Gamas
	 * @return List
	 */
	@RequestMapping(value = "gamasAlta/obtenerGamasAlta", method = RequestMethod.POST)
	public @ResponseBody
	List<Gamas> obtenerGamasAlta(@ModelAttribute Gamas filterGamas) {
		GamasController.logger
				.info("[GET - obtenerGamasAlta] : Obtener Gamas en Alta");
		filterGamas.setBaja("0");
		return this.gamasService.findAll(filterGamas, null);
	}
}
