package cn.quantgroup.xyqb.service.captcha.impl;

import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.model.ClientType;
import cn.quantgroup.xyqb.service.captcha.GeetestLib;
import cn.quantgroup.xyqb.service.captcha.IGeetestCaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author xufei on 2018/1/30.
 */
@Service
@Slf4j
public class GeetestCaptchaServiceImpl implements IGeetestCaptchaService {


    @Value("${geetest.captcha.id}")
    private String captchaId;

    @Value("${geetest.private.key}")
    private String privateKey;

    @Value("${geetest.new.fail.back}")
    private boolean newFailback;

    @Value("${geetest.api.url}")
    private String apiUrl;

    @Override
    public Map<String, String> fetchGeetestCaptcha(String markId, String remoteIp, ClientType clientType) {
        HashMap<String, String> param = getParam(markId, remoteIp, clientType);
        return getGeetestSdk().getResponseStr(param);
    }

    @Override
    public boolean validGeetestCaptcha(String markId, String remoteIp, ClientType clientType, String challenge, String validate, String seccode) {
        HashMap<String, String> param = getParam(markId, remoteIp, clientType);
        int gtResult = getGeetestSdk().enhencedValidateRequest(challenge, validate, seccode, param);
        return Constants.GT_CAPTCHA_VALIDATE_SUCCESS == gtResult;
    }

    private GeetestLib getGeetestSdk() {
        return new GeetestLib(captchaId, privateKey, newFailback, apiUrl);
    }

    private HashMap<String, String> getParam(String markId, String remoteIp, ClientType clientType) {
        HashMap<String, String> param = new HashMap<>();
        param.put("user_id", markId);
        if (Objects.isNull(clientType)) {
            param.put("client_type", ClientType.APP.getAlias());
        } else {
            param.put("client_type", clientType.getAlias());
        }
        param.put("ip_address", remoteIp);
        return param;
    }
}
