
const GOOGLE_OAUTH_TOKEN_URI = "https://www.googleapis.com/oauth2/v4/token"
    ,GOOGLE_USERINFO_URI = "https://www.googleapis.com/oauth2/v1/userinfo";

const googleConfig = require('../config.js').login.google
    ,httpsRequest = require('./httpsRequest.js').httpsRequest
    ,httpsPost = require('./httpsRequest.js').httpsPost
;

function getUserId(code, cb) {
    httpsPost(GOOGLE_OAUTH_TOKEN_URI, {
        "client_id": googleConfig.clientId
        ,"client_secret": googleConfig.clientSecret
        ,"redirect_uri": googleConfig.redirect_uri
        ,"grant_type": "authorization_code"
        ,"code": code
    },
    (status, resp) => {
        if (status === 200 && resp && resp.access_token) {
            httpsRequest(GOOGLE_USERINFO_URI +"?access_token="+resp.access_token,
            (status, resp) => {
                if (status === 200 && resp && resp.id) {
                    cb(resp.id);
                } else {
                    cb(null);
                }
            });
        } else {
            cb(null);
        }
    });
}

module.exports.GoogleOAuth = {
    getUserId: getUserId
};

