package com.zksy.framework.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zksy.common.utils.StringUtils;
import com.zksy.common.utils.result.Response;
import com.zksy.common.utils.sign.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;

@Component
public class ComfirmClientInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;
    @Value("${clientKey}")
    private String CLIENT_KEY;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String s = request.getHeader("Loveandpeace");
        int i = LocalDate.now().getDayOfMonth();
        String key = CLIENT_KEY+i;
        String k = Md5Utils.hash(key);
        if(!k.equals(s)){
            response.setStatus(403);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(Response.error(403,"不准请求")));
            return false;
        }
//        String ua = request.getHeader("User-Agent");
//        if(StringUtils.isEmpty(ua) || !isBrowser(ua)){
//            response.setStatus(403);
//            response.setContentType("text/html;charset=UTF-8");
//            response.getWriter().write(objectMapper.writeValueAsString(Response.error(403,"不准请求")));
//            return false;
//        }
        return true;
    }

//    private boolean isBrowser(String userAgent) {
//        return userAgent.contains("Mozilla") &&
//                (userAgent.contains("Chrome") ||
//                        userAgent.contains("Safari") ||
//                        userAgent.contains("Firefox") ||
//                        userAgent.contains("Opera"));
//    }
}
