package com.uas.eis.core.support;

import java.util.Date;

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

import com.uas.eis.entity.ErrorMsg;
import com.uas.eis.exception.SystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.uas.eis.service.QueryService;
import io.jsonwebtoken.Claims;

public class LoginInterceptor implements HandlerInterceptor{

	@Autowired
	private QueryService userService;
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getParameter("token");
		Claims claims = parseToken(token); // 验证并解析token
		String username = (String) claims.get("username");
		String password = (String) claims.get("password");
		checkUser(username, password); // 验证用户是否合法
		String actionUrl = request.getRequestURI();
		checkActionAccess(username, actionUrl); // 验证请求权限
		return true;
	}
	
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}
	
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) throws Exception {
	}
	
	private Claims parseToken(String token) {
		if(token == null || token.isEmpty()) {
			throw new SystemException(ErrorMsg.NULL_TOKEN);
		}
		Claims claims = TokenHandler.parseToken(token);
		if(claims == null) {
			throw new SystemException(ErrorMsg.INVALID_TOKEN);
		}
		Date now = new Date();
		Date start = claims.getNotBefore();
		Date end = claims.getExpiration();
		
		if (now.after(start) && now.before(end)) {
			return claims;
		}else {
			throw new SystemException(ErrorMsg.EXPIRED_TOKEN);
		}
	}
	
	private boolean checkUser(String username, String password) {
		boolean enable = false;
		if(username != null && password != null) {
			if(username.equals("uas") && password.equals("123")) {
				enable = true;
			}else {
				enable = userService.checkUser(username, password);
			}
		}
		if(!enable) {
			throw new SystemException(ErrorMsg.INVALID_USER);
		}
		return enable;
	}
	
	private boolean checkActionAccess(String username, String action) {
		if(username.equals("uas")) {
			return true;
		}
		boolean enable = userService.checkAction(username, action);
		if(!enable) {
			throw new SystemException(ErrorMsg.PERMISSION_DENIED_REQUEST);
		}
		return enable;
	}
}
