package com.sonic.sdk.api.filters;

import com.alibaba.fastjson.JSON;
import com.sonic.sdk.api.exceptions.ApiRequestTimeOutException;
import com.sonic.sdk.api.exceptions.DecryptFailException;
import com.sonic.sdk.api.utils.http.DecryptRequestBodyWrapper;
import com.sonic.sdk.api.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * requestBody 解密 filter
 * 用于通用解密
 */
public class DecryptRequestBodyFilter implements Filter {

    @Value("${spring.profiles.active:prod}")
    private String profile;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        //排除dev local 环境.
        boolean local = "local".equals(profile) ;
        if (request instanceof HttpServletRequest &&  !local) {
            try {
                requestWrapper = new DecryptRequestBodyWrapper((HttpServletRequest) request);
            } catch (DecryptFailException e) {
                Result r = new Result();
                r.setContent(null);
                r.setStatus("ERROR");
                r.setErrorCode("ERROR");
                r.setErrorMsg("Request parameter decryption failed");
                String resp = JSON.toJSONString(r);
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.setCharacterEncoding("Utf-8");
                response.getWriter().write(resp);
                response.getWriter().flush();
                return;
            } catch (ApiRequestTimeOutException e) {
                Result r = new Result();
                r.setContent(null);
                r.setStatus("ERROR");
                r.setErrorCode("ERROR");
                r.setErrorMsg("Request timeout");
                String resp = JSON.toJSONString(r);
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.setCharacterEncoding("Utf-8");
                response.getWriter().write(resp);
                response.getWriter().flush();
                return;
            }
        }
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }


    @Override
    public void init(FilterConfig filterConfig) {
    }
}
