package com.sonic.frog.client.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.sonic.common.exception.SysException;
import com.sonic.common.rpc.GlobalResultCode;
import com.sonic.frog.client.GoogleOauth2Client;
import com.sonic.frog.domain.bo.ThirdAuthBo;
import com.sonic.frog.enums.BizResultCode;
import com.sonic.frog.enums.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * google oauth2
 * @author code
 */
@Slf4j
@Service
public class GoogleOauth2ClientImpl implements GoogleOauth2Client {

    @Value("${thirdLogin.gmail.authUrl}")
    private String gmailAuthUrl;
    @Value("${thirdLogin.gmail.client.webId}")
    private String gmailWebClientId;
    @Value("${thirdLogin.gmail.client.iosId}")
    private String gmailIosClientId;
    @Value("${thirdLogin.gmail.client.androidId}")
    private String gmailAndroidClientId;

    @Override
    public ThirdAuthBo getGoogleIdByToken(String token) {
        String result;
        try {
            result = Unirest.get(gmailAuthUrl + token).asString().getBody();
            log.info("===> getGoogleIdByToken : {}", result);
        } catch (UnirestException e) {
            throw new SysException(GlobalResultCode.SYSTEM_EXCEPTION, e);
        }

        log.info("===> getGoogleIdByToken result : {}", result);
        JSONObject jsonObject = JSON.parseObject(result);
        // 验证aud 是否为应用ID，只有当aud的值和我们配置的只匹配时才能确认时我们的应用，才可以使用
        BizResultCode.AUTH_FAIL.check(!gmailIosClientId.equals(jsonObject.getString(Constants.AUD))
                && !gmailWebClientId.equals(jsonObject.getString(Constants.AUD))
                && !gmailAndroidClientId.equals(jsonObject.getString(Constants.AUD)));

        String googleId = jsonObject.getString("sub");
        BizResultCode.GOOGLE_ID_GET_ERROR.check(StringUtils.isEmpty(googleId));

        ThirdAuthBo bo = new ThirdAuthBo();
        //设置googleId
        bo.setThirdId(googleId);

        //获取用户邮箱 我们只获取被用户认证通过的邮箱，未认证的邮箱没有太多作用，所以不获取
        String emailVerified = jsonObject.getString("email_verified");
        if(Boolean.TRUE.toString().equals(emailVerified)) {
            String email = jsonObject.getString("email");
            //设置用户邮箱
            bo.setEmail(email);
        }
        return bo;
    }
}
