package cn.iselab.mooctest.user.web.logic.impl;

import cn.iselab.mooctest.user.configure.ThirdPartyAuthConfiguration;
import cn.iselab.mooctest.user.constants.ResponseStatus;
import cn.iselab.mooctest.user.constants.UrlConstants;
import cn.iselab.mooctest.user.data.ResponseResult;
import cn.iselab.mooctest.user.data.UserInfo;
import cn.iselab.mooctest.user.model.UserThirdParty;
import cn.iselab.mooctest.user.service.ThirdPartyAuthService;
import cn.iselab.mooctest.user.web.logic.BaseLogic;
import cn.iselab.mooctest.user.web.logic.ThirdPartyLogic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 第三方验证等
 * @Author: xuexb
 * @CreateDate: 19-1-10$ 上午1:25$
 */
@Service
public class ThirdPartyLogicImpl extends BaseLogic implements ThirdPartyLogic {

    @Autowired
    ThirdPartyAuthService thirdPartyAuthService;

    @Autowired
    ThirdPartyAuthConfiguration thirdPartyAuthConfiguration;

    @Override
    public ResponseResult<Object> loginByGithub(String code, HttpServletRequest request) {
        ResponseResult<Object> result = new ResponseResult<>();
        UserInfo userInfo = null;
        try{
            userInfo = thirdPartyAuthService.getGithubUserInfo(UrlConstants.GET_GITHUB_USER_INFO
                    , thirdPartyAuthService.getAccessToken(UrlConstants.GET_GITHUB_LOGIN_ACCESSTOKEN
                                    .replace("CLIENTID", thirdPartyAuthConfiguration.getGitHubClientId())
                                    .replace("CLIENTSECRET", thirdPartyAuthConfiguration.getGitHubClientSecret())
                            , code));
        }catch (Exception e){
            result.init(ResponseStatus.FAILED, "获取第三方用户信息出错", null);
            LOG.error(result.getMsg(), e);
            return result;
        }
        UserThirdParty userThirdParty = thirdPartyAuthService.findByThirdIdAndType(userInfo.getThirdPartyId(), "github");
        if (userThirdParty == null){
            result.init(ResponseStatus.NOTFOUND, "未绑定mooctest帐号", userInfo);
            LOG.info(result.getMsg());
            return result;
        }
        result.init(ResponseStatus.SUCCESS, "登录成功", userThirdParty);
        request.getSession().setAttribute("userId", userThirdParty.getUserId()+"");
        LOG.info(result.getMsg());
        return result;
    }
}
