package com.leanwo.activiti.config;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.leanwo.activiti.db.AccountManagementService;
import com.leanwo.activiti.service.base.TokenService;

@Component
public class TokenInterceptor implements HandlerInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
	
	@Inject
	private TokenService tokenService;
	
	@Inject
	private AccountManagementService accountManagementService; 
	
	
	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object handler) throws Exception {
		
		// 获取我们请求头中的token验证字符
		String tokenHeader = httpServletRequest.getHeader("token");		
		if (tokenHeader == null) {
			logger.info("请求头中不存在token参数");
			outputNoRole(httpServletResponse, 401, "请求头中不存在token参数");
			return false;
		}

		String accountHeader = httpServletRequest.getHeader("account");
		if (accountHeader == null) {
			logger.info("请求头中不存在account参数");
			outputNoRole(httpServletResponse, 401, "请求头中不存在account参数");
			return false;
		}

		Long accountId = Long.parseLong(accountHeader);
		tokenService.parseLoginContext(tokenHeader, accountId);
		
		accountManagementService.loadAccountManagement(false);
		
		// String data = ReadAsChars(httpServletRequest);
		return true;		
	}

    public String readAsChars(HttpServletRequest request)
    {
        InputStream is = null;
        try
        {
            is = request.getInputStream();
            StringBuilder sb = new StringBuilder();
            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1;)
            {
                sb.append(new String(b, 0, n));
            }
            return sb.toString();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != is)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return null; 
    }
    
	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object o, Exception e) throws Exception {
	}

	private void outputNoRole(HttpServletResponse response, int httpStatus, String message) {
		response.setStatus(httpStatus);
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/plain; charset=utf-8");
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			outputStream.write(message.getBytes("utf-8"));
			outputStream.flush();
		} catch (IOException e) {
			logger.error("Filter异常", e);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					logger.error("Filter输出流关闭失败。", e);
				}
			}
		}
	}
}
