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

import java.io.IOException;
import java.util.List;

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

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.service.base.WarehouseManager;
import com.dev.energy.server.model.security.User;
import com.dev.energy.server.service.security.UserManager;

/**
 * @author  dev
 */
public class WarehouseServlet extends HttpServlet{
	protected static ApplicationContext ac;
	
	public void init(ServletConfig sc) throws ServletException {
		super.init(sc);
		ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc.getServletContext());
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req , res);
	}
	
	protected void doPost(final HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		WarehouseManager warehouseManager = (WarehouseManager) ac.getBean("warehouseManager");
		// -> add by shimu.liang
		final String loginName = req.getParameter("login_name");
		final UserManager userManager = (UserManager) ac.getBean("userManager");
		User user = userManager.retrieve(loginName);
		//如果用户为空
		if(user == null) {
			res.getOutputStream().write("".getBytes("UTF-8"));
			return;
		}
		List<Warehouse> warehouses = null;
		//管理员就load全部warehouse,其它类型用户从userWarehouse中获取
		if(!userManager.isAdmin(user)) {
			warehouses = warehouseManager.getAvailableWarehousesByUserId(user.getId());
		} else {
			warehouses = warehouseManager.loadAll(Warehouse.class);
		}
		
		// <-
		
		StringBuffer response = new StringBuffer();
		for(int i = 0, n = warehouses.size() ;i < n;i ++){
			Warehouse warehouse = warehouses.get(i);
			if (!warehouse.isDisabled()) {
				response.append(warehouse.getCode());
				response.append(",");
				response.append(warehouse.getName());
				if(i != n - 1){
					response.append("|");
				}
			}
		}
		String strRes = response.toString();
		res.setContentType("text/html; charset=utf-8");
		res.getOutputStream().write(strRes.getBytes("UTF-8"));
	}

}
