package com.jpsoft.shinestar.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

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

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")){
            return true;
        }

        String token = request.getHeader("Authorization");

        if (StringUtils.isEmpty(token)){
            token = (String)request.getSession().getAttribute("token");
        }

        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }

        boolean result = false;

        try {
            String userId = JwtUtil.decodeToken(jwtSecret,token);

            request.setAttribute("subject",userId);

            result = true;
        }
        catch(Exception ex){
            MessageResult<String> msgResult = new MessageResult<>();

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
            msgResult.setCode(415);

            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(msgResult);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("access-control-allow-origin","*");
            response.getWriter().print(json);

            result = false;
        }

        return result;
    }
}
