package com.ejie.y42b.validation;

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

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import com.ejie.x38.util.DateTimeManager;
import com.ejie.x38.util.StackTraceManager;

/**
 * 
 *  
 * 
 */
public class Y42bValidationServlet implements HttpRequestHandler {

	private Y42bValidationManager validationManager;
	private CookieLocaleResolver localeResolver;

	private static final long serialVersionUID = 1L;
	private final static Logger logger = LoggerFactory
			.getLogger(Y42bValidationServlet.class);

	@Override
	public void handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		logger.info("The request is a validation. Validation begins.333333333333333333333333333333");

		try {
			int language = localeResolver.getCookieName().length() + 1;
			logger.info("language= "+language);

			int languageIndex = request.getHeader("Cookie").indexOf(
					localeResolver.getCookieName())
					+ language;
			logger.info("languageIndex= "+languageIndex);
			
			Locale locale = new Locale(request.getHeader("Cookie").substring(
					languageIndex, languageIndex + 2));// (request.getHeader("Cookie").indexOf(";"))));

			logger.info("locale= "+(locale==null?"null":locale));
			
			String data = "";
			String bean = "";
			String group = "";
			Enumeration e = request.getParameterNames();
			while (e.hasMoreElements()) {
				String param = e.nextElement().toString();

				if (param.equals("bean")) {
					bean = request.getParameter(param);
				} else if (param.equals("group")) {
					group = request.getParameter(param);
				} else if (param.equals("data")) {
					data = request.getParameter(param);
				}
			}

			String result = null;
			logger.info("bean=="+(bean==null?"null":bean));
			logger.info("group=="+(group==null?"null":group));
			logger.info("data=="+(data==null?"null":data));
			
			if ("".equals(group) || group == null) {
				logger.info("if group");
				try{
					result = validationManager.validateObject(bean, data, locale);	
				}catch(Throwable th){
					logger.info("error.conprinttrace333333333333333333333333333333");
					th.printStackTrace();
					logger.error(StackTraceManager.getStackTrace(th));
				}

			} else {
				logger.info("else group");
				result = validationManager.validateObjectGroup(bean, data,
						group, locale);
			}
			logger.info("despues validate 1");
			response.setContentType("text/javascript;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			logger.info("despues validate 2");
			response.setHeader("Expires", DateTimeManager.getHttpExpiredDate());
			logger.info("despues validate 3");

			logger.info("0"+ (result==null?"null":result));
			
			if (result == null) {
				logger.info("1");
				response.setStatus(HttpServletResponse.SC_OK);
			} else if (result != null && !result.equals("error!")) {
				logger.info("2");
				response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
				response.getWriter().write(result);
			} else {
				logger.info("3");
				throw new RuntimeException("error!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(StackTraceManager.getStackTrace(e));
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.getWriter()
					.write("Error in the validate. The structure or morphology of the data is incorrect, review the data sent.");
		}

		logger.debug("Exit from the Validation Servlet.");
	}

	// Getters & Setters
	public Y42bValidationManager getValidationManager() {
		return validationManager;
	}

	public void setValidationManager(Y42bValidationManager validationManager) {
		this.validationManager = validationManager;
	}

	public void setLocaleResolver(CookieLocaleResolver localeResolver) {
		this.localeResolver = localeResolver;
	}
}
