package com.dev.swms.server.web.servlet;

import java.io.IOException;

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

import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.service.base.WarehouseManager;
import com.dev.energy.server.exception.AuthenticationException;
import com.dev.energy.server.exception.EnergyServerRuntimeException;
import com.dev.energy.server.model.security.User;
import com.dev.energy.server.service.security.SecurityFilter;
import com.dev.energy.server.servlet.LoginServlet;
import com.dev.energy.server.util.Constant;
import com.dev.energy.server.util.LocalizedMessage;

public class SWMSLoginServlet extends LoginServlet {
	
	/** 当前仓库*/
	public static final String SESSION_WAREHOUSE = "SESSION_WAREHOUSE"; //key=SESSION_WAREHOUSE
	public static final String SESSION_WAREHOUSE_ID = "SESSION_WAREHOUSE_ID"; //key=SESSION_WAREHOUSE_ID
	
	protected void doPost(final HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		final String loginName = req.getParameter("login_name");
		final String password = req.getParameter("password");
		final String warehouse = req.getParameter("warehouse");
		final Warehouse wh = queryWarehouse(loginName);
		final String referenceModel = wh.getReferenceModel();
		final String locale = req.getParameter("locale");

		User loginUser = null;
		try {
			loginUser = authenticateUser(loginName,password,referenceModel,locale);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			String hintMsg = LocalizedMessage.getLocalizedMessage(e.getClass().getSimpleName(),referenceModel,locale);
			res.getOutputStream().write(hintMsg.getBytes("UTF-8"));
			return;
		}
		res.getOutputStream().write("success".getBytes());
		
		SecurityFilter sf = buildSecurityFilter(loginUser, referenceModel, locale);
		HttpSession session = req.getSession(true);
		session.setAttribute(Constant.SECURITY_FILTER_IN_SESSION , sf);//权限过滤器
		session.setAttribute(Constant.USER_IN_SESSION , loginUser);//当前用户
		session.setAttribute(SESSION_WAREHOUSE , wh);//当前的仓库
		session.setAttribute(SESSION_WAREHOUSE_ID , wh.getId());//当前的仓库
		session.setAttribute(MODELTYPE , referenceModel);//当前参考模型
		session.setAttribute(LOCALE,locale);//当前语言环境		
		session.setAttribute(Constant.MODULE , "e2wms");
//		SecurityContextHolder.addSecurityContext(req.getSession());
	}

	private Warehouse queryWarehouse(String loginName) {
		WarehouseManager warehouseManager = (WarehouseManager) ac.getBean("warehouseManager");
		Warehouse wh = warehouseManager.getWarehouseByLoginName(loginName);
		if(wh == null){
			throw new EnergyServerRuntimeException("No warehouse avaliable for user [" + loginName + "].");
		}
		return wh ;
	}

}
