package com.skyversation.poiaddr.util;

import com.skyversation.poiaddr.entity.PYToken;
import com.skyversation.poiaddr.entity.VerifyBean;
import com.skyversation.poiaddr.util.net.NetTools;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class PYVerify {

    private static PYVerify instance = new PYVerify();
    private PYVerify() {}
    public static PYVerify getInstance() {
        return instance;
    }

    public VerifyBean verify(HttpServletRequest request, String token, String servertype) {
        // 包含token合法验证、次数验证、失效验证
        PYToken pyToken = NetTools.getInstance().verifyPYToken(token,servertype);
        if(!StringUtils.isEmpty(pyToken.getErrorMsg())){
            return new VerifyBean(false, pyToken.getErrorMsg());
        }
        if(pyToken == null){
            return new VerifyBean(false,
                    MessageManage.getInstance().getResultContent(Constant.FAILURE_TOKEN, "无效token", "无效token"));
        }
        // token验证通过，开始验证ip地址和请求是否有授权
        if(!pyToken.getIpAddress().contains("0.0.0.0")){
            String ip = NetTools.getIpAddress(request);
            if(!pyToken.getIpAddress().contains(ip)){
                return new VerifyBean(false,
                        MessageManage.getInstance().getResultContent(Constant.IP_NOT_PASS, "ip验证不通过", "ip验证不通过"));
            }
        }
        // ip验证通过，开始验证请求事项
        if(!pyToken.getMatterName().contains("ALL")){
            if(!pyToken.getMatterName().contains(servertype)){
                return new VerifyBean(false,
                        MessageManage.getInstance().getResultContent(Constant.MATTER_NOT_PASS, "事项验证不通过", "事项验证不通过"));
            }
        }
        return new VerifyBean(true, null);
    }

}
