package com.ejie.ab78.control.inicio;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.DelegatingFilterProxy;

import com.ejie.ab78.model.expedientes.Expedientes;
import com.ejie.ab78.service.expedientes.ExpedientesService;

/**
 * Servlet Filter implementation class TramitaguteFilter
 */
@Component("tramitaguneFilter")
public class TramitaguneFilter extends DelegatingFilterProxy implements Filter {

	@Autowired
	private ExpedientesService expedientesService;

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

	/**
	 * Default constructor.
	 */
	public TramitaguneFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String folderId = request.getParameter("folderId");
		String folderNumber = request.getParameter("folderNumber");
		// String fechaSolicitud = request.getParameter("fechaSolicitud");
		// String folderDescription = request.getParameter("folderDescription");
		// String dni = request.getParameter("dni");
		// String tipoExpediente = request.getParameter("tipoExpediente");
		// String tramite = request.getParameter("tramite");
		// String tarea = request.getParameter("tarea");
		String idioma = request.getParameter("idioma");

		logger.info("Redirigiendo expediente - FolderID: %s, FolderNumber: %s", folderId, folderNumber);

		if (idioma != null && !"".equals(idioma)) {
			Locale locale = new Locale(idioma);
			LocaleContextHolder.setLocale(locale);
		}
		Expedientes expedientes = new Expedientes();
		expedientes.setFolderId(folderId);
		expedientes = this.expedientesService.findByFolderId(expedientes);

		HttpServletResponse resp = (HttpServletResponse) response;
		if (expedientes != null) {
			resp.sendRedirect("/ab78WebAppWar/denuncias/ficha-denuncia/" + expedientes.getFolderId());
		} else {
			logger.error("No se ha encontra la denuncia para el expediente %s", folderId);
			resp.sendRedirect("/ab78WebAppWar/denuncias/expediente-error/" + folderId);
		}
		// pass the request along the filter chain
		// chain.doFilter(request, response);
	}

}
