package informesServlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

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

import m05bClasses.m05bConstantesInformes;
import m05bIdioma.m05bCResources;
import m05bServices.m05bCTKService;
import m05bServices.m05bVistaVehiculosService;
import n05bModelosVistas.m05bOption;

import org.apache.log4j.Logger;

public class m05bAjaxControllerServlet extends
		javax.servlet.http.HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4982885644901979955L;

	java.sql.Connection conn = null;

	public static final String FO_REQUEST_PARAM = "fo";

	private static Logger logger = Logger
	.getLogger(m05bAjaxControllerServlet.class);
	public void doPost(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException {
		try {
			doGet(request, response);
		} catch (Exception e) {
			////miLog.addTraza(e);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		performTask(request, response);
	}

	/**
	 * Initializes the servlet.
	 */
	public void init() {
		// insert code to initialize the servlet here

	}

	/**
	 * Realiza la función de controlador de informes
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void performTask(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws ServletException, IOException {

		// Se obtiene el tipo informe y el formato
		logger.info("Llamada a AJAX");
			int ajaxTipo = Integer.parseInt(request
					.getParameter("tipo"));
			if(ajaxTipo==0)
				createAjax(request, response);
			else if(ajaxTipo==1)
				callCargar(request,response);
			else
				callCargarKilometrajes(request,response);
		
	}

	/**
	 * Carga la tabla de kilometrajes 
	 * @param request
	 * @param response
	 */
	private void callCargarKilometrajes(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response){
		//Rellenar la tabla temporal
		logger.info("Se pide cargar la tabla de kilometrajes");
		
	
		//callCargar(request,response);
		logger.info("Obtener el usuario");
		
		 HttpSession session = request.getSession(true);
		
			
			String idioma=	"";
			try{
				idioma=	((m05bCResources)	session.getAttribute("IdiomaActual")).getIdiomaActual();
				}
				catch(Exception e){
					idioma=m05bConstantesInformes.CASTELLANO;
				}
		   String persona = (String) session.getAttribute("persona");
		   String personaCodigo = (String) session.getAttribute("personaCodigo");
		   logger.info("Usuario="+persona+" codigo="+personaCodigo);
		   String fechaInit=request.getParameter("fechadesde");
			String fechaFin=request.getParameter("fechahasta");
			logger.info("Fecha inicio"+fechaInit);
			logger.info("Fecha fin"+fechaFin);
			m05bCTKService.getInstance().callRellenarKilometrajes(personaCodigo,fechaInit,fechaFin,idioma,-1);
	
	}
	/**/
	private void callCargar(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response){
		logger.info("Se pide cargar la tabla de transferencias");
		//Rellenar la tabla temporal
		HttpSession session = request.getSession(true);
		 String actualizado = 
		    (String)session.getAttribute("actualizadaTransferencias");
		
		  if (actualizado == null ||(actualizado != null && !actualizado.equals("hecho"))) {
	
			  session.setAttribute("actualizadaTransferencias", "hecho");
				m05bCTKService.getInstance().callRellenar();
		  } 
	
	}
	private void createAjax(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws ServletException, IOException {

		// 4. Set response type to JSON
		response.setContentType("application/json");
		HttpSession session = request.getSession(true);
		String idioma=	"";
		try{
			idioma=	((m05bCResources)	session.getAttribute("IdiomaActual")).getIdiomaActual();
			}
			catch(Exception e){
				idioma=m05bConstantesInformes.CASTELLANO;
			}
		String salida = toJson(m05bVistaVehiculosService.getInstance()
				.getModelos(request.getParameter("marcas"),idioma,-1));
		// 6. Send List<Article> as JSON to client
		response.getWriter().write(salida);

	}

	private String toJson(ArrayList<m05bOption> options) {

		StringBuffer str = new StringBuffer();

		// "employees": [
		// { "firstName":"John" , "lastName":"Doe" },
		// { "firstName":"Anna" , "lastName":"Smith" },
		// { "firstName":"Peter" , "lastName":"Jones" }
		// ]
		// }
		str.append("{\"salida\":[");
		Iterator<m05bOption> iter = options.iterator();
		int i = 0;
		m05bOption current;
		while (iter.hasNext()) {
			current = iter.next();
			if (i != 0) {
				str.append(",");
			}
			str.append("{\"val\":\"");
			str.append(current.getValue());
			str.append("\", \"text\":\"");
			str.append(current.getText());
			str.append("\"}");
			i++;
		}
		str.append("]}");
		return str.toString();

	}

}
