'use strict';

/**
 * 验证码
 *
 * @author CaiAoLin
 * @date 2017/10/13
 * @version
 */
// import Request from "request";
const Geetest = require('gt3-sdk');

class Captcha {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        this.captcha = new Geetest({
            geetest_id: '697bb3d9c16ab6d016c375f0a65e805b',
            geetest_key: '1bde862a0898a7c72ffb82e95a0816c7',
        });
    }

    /**
     * 验证码注册
     *
     * @return {String} - 返回生成所需的json数据
     */
    async register(request) {
        let response = {
            success: 0,
        };
        try {
            const data = await this.captcha.register(null);
            request.session.fallback = !data.success;
            response = data;
        } catch (error) {
            response.success = 0;
            response.message = error;
            JSON.stringify(response);
        }

        return response;
    }

    /**
     * 验证码校验
     *
     * @return {Boolean} - 返回是否校验成功
     */
    async validate(request) {
        let result = false;

        const challenge = request.body.geetest_challenge;
        const validate = request.body.geetest_validate;
        const seccode = request.body.geetest_seccode;

        try {
            if (challenge === '' || validate === '' || seccode === '') {
                throw '参数错误';
            }
            const fallback = request.session.fallback;

            result = await this.captcha.validate(fallback, {
                geetest_challenge: challenge,
                geetest_validate: validate,
                geetest_seccode: seccode,
            });

        } catch (error) {
            result = false;
        }

        return result;
    }
}

module.exports = Captcha;
