package com.uas.core.support;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	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;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
	}

	@Override
	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 =true; /*userService.checkAction(username, action);*/
		if(!enable) {
			throw new SystemException(ErrorMsg.PERMISSION_DENIED_REQUEST);
		}
		return enable;
	}
}
