package com.ejie.y42b.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

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

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.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
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.SessionAttributes;

import com.ejie.x38.control.exception.ControlException;
import com.ejie.y42b.UserPreferences;
import com.ejie.y42b.constantes.Y42bAgendaConstantes;
import com.ejie.y42b.forms.mant.Y42bFormArbol;
import com.ejie.y42b.model.Y42bTree;
import com.ejie.y42b.service.Y42bArbolService;
import com.ejie.y42b.utils.Y42bProcessTree;

/**
 * ConsultasServiceImpl  
 * 
 *  
 */

@Controller()
@RequestMapping(value = "/arbol")
@SessionAttributes(value = { "frmArbol" })
public class Y42bArbolController {

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

	@Autowired()
	private Y42bArbolService arbolService;

	@Autowired()
	private Properties appConfiguration;

	/**
	 * /** Method 'getNodeInfo'. Recoje el id del nodo seleccionado y lo mete en
	 * session
	 * 
	 * @param id
	 *            String
	 * @param mySession
	 *            session
	 * @return String nodeid
	 */
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody()
	String setNodeInfo(@RequestParam(value = "id", required = false) String id,
			HttpSession mySession) {

		UserPreferences userPreferences = (UserPreferences) mySession
				.getAttribute(Y42bAgendaConstantes.SESSIONBEAN_NODE);
		// userPreferences.setNodeActive(id);
		mySession.setAttribute(Y42bAgendaConstantes.SESSIONBEAN_NODE,
				userPreferences);
		Y42bArbolController.logger.debug("Set Node info: "
				+ userPreferences.getNodeActive());

		return userPreferences.getNodeActive();
	}

	/**
	 * /** Method 'getNodeInfo'. Devuelve el nodo en sesion
	 * 
	 * @param mySession
	 *            Session
	 * @return String nodeid
	 */
	@RequestMapping(value = "obtenerNodoActivo", method = RequestMethod.GET)
	public @ResponseBody()
	String getNodeInfo(HttpSession mySession) {

		UserPreferences userPreferences = (UserPreferences) mySession
				.getAttribute(Y42bAgendaConstantes.SESSIONBEAN_NODE);
		String nodeId = userPreferences.getNodeActive();
		Y42bArbolController.logger.debug("Get Node info: " + nodeId);

		return nodeId;
	}

	/**
	 * Loading Main tree
	 * 
	 * @param mySession
	 *            httpSession
	 * @param request
	 *            request
	 * @param response
	 *            response
	 * @throws IOException
	 *             io
	 */
	@RequestMapping(value = "ajaxTree", method = RequestMethod.GET)
	public void getAjax(HttpSession mySession, HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		response.setCharacterEncoding("ISO-8859-1");
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/html;charset=utf-8");

		PrintWriter out = response.getWriter();
		// String node = "";

		UserPreferences userPreferences = (UserPreferences) mySession
				.getAttribute(Y42bAgendaConstantes.SESSIONBEAN_NODE);
		boolean mostrarNoActivas = userPreferences
				.isMostrarEntidadesNoActivas();
		Y42bArbolController.logger
				.debug("Arbol******************************************");

		String estadoActivas = "";

		if (mostrarNoActivas) {
			estadoActivas = Y42bAgendaConstantes.ESTADO_TODAS;
		} else {
			estadoActivas = Y42bAgendaConstantes.ESTADO_ACTIVAS;
		}

		// Y42bTree arbol = this.arbolService.obtenerArbol(mostrarNoActivas);
		// arbol.setMostrarNoActivas(mostrarNoActivas);

		Y42bTree arbol = this.arbolService.obtenerArbol(estadoActivas);
		arbol.setEstadoActivas(estadoActivas);

		// arbol.setNodeActive(userPreferences.getNodeActive());
		String json = Y42bProcessTree.obtieneJsonArbol(arbol);
		Y42bArbolController.logger
				.debug("******************************************");
		Y42bArbolController.logger.debug("Arbol: ");
		Y42bArbolController.logger.debug(json);
		Y42bArbolController.logger
				.debug("******************************************");
		out.println(json);
		out.flush();
		out.close();

	}

	/**
	 * Loading Main tree
	 * 
	 * @param formArbol
	 *            Y42bFormArbol
	 * 
	 * @param result
	 *            BindingResult
	 * @param mySession
	 *            session
	 * @param model
	 *            modle
	 * @return ret
	 * @throws IOException
	 *             io
	 */
	@RequestMapping(value = "refrescar", method = RequestMethod.POST)
	public String getRefrescar(
			@ModelAttribute("arbolForm") Y42bFormArbol formArbol,
			BindingResult result, HttpSession mySession, Model model)
			throws IOException {

		UserPreferences userPreferences = (UserPreferences) mySession
				.getAttribute(Y42bAgendaConstantes.SESSIONBEAN_NODE);
		boolean mostrarNoActivas = formArbol.isChkShowEntidadesNoActivas();

		String url = "";

		if (Y42bAgendaConstantes.SECCION_BUSCADOR
				.equals(formArbol.getSeccion())) {
			url = "redirect:../buscador/vista";
		} else {
			url = "redirect:../mant/vista";
		}

		userPreferences.setMostrarEntidadesNoActivas(mostrarNoActivas);
		mySession.setAttribute(Y42bAgendaConstantes.SESSIONBEAN_NODE,
				userPreferences);

		return url;

	}

	/**
	 * Method 'handle'.
	 * 
	 * @param e
	 *            ControlException
	 * @return String
	 * 
	 */
	@ExceptionHandler()
	public @ResponseBody()
	String handle(ControlException e) {
		Y42bArbolController.logger.warn(e.getMessage());
		return e.getMessage();
	}

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

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

}