
const FACEBOOK_OAUTH_TOKEN_URI = "https://graph.facebook.com/v2.9/oauth/access_token"
    FACEBOOK_OAUTH_TOKEN_APP = "https://graph.facebook.com/oauth/access_token"
    ,FACEBOOK_OAUTH_TOKEN_INFO = "https://graph.facebook.com/debug_token";

const facebookConfig = require('../config.js').login.facebook
    ,httpsRequest = require('./httpsRequest.js').httpsRequest
    ,httpsPost = require('./httpsRequest.js').httpsPost
;

function getAppToken(cb) {
    httpsRequest(FACEBOOK_OAUTH_TOKEN_APP
        +"?client_id=" +facebookConfig.clientId
        +"&client_secret=" +facebookConfig.clientSecret
        +"&grant_type=client_credentials",
        (status, resp) => {
            if (status === 200 && resp && resp.access_token) {
                cb(resp.access_token);
            } else {
                cb(null);
            }
    });
}

function getUserId(code, cb) {
    httpsRequest(FACEBOOK_OAUTH_TOKEN_URI
        +"?client_id=" +facebookConfig.clientId
        +"&client_secret=" +facebookConfig.clientSecret
        +"&redirect_uri=" +facebookConfig.redirect_uri
        +"&code=" +code,
    (status, resp) => {
        if (status === 200 && resp && resp.access_token) {
            getAppToken((appToken) => {
                if (appToken) {
                    httpsRequest(FACEBOOK_OAUTH_TOKEN_INFO +"?input_token="+resp.access_token +"&access_token=" +appToken,
                    (status, resp) => {
                        if (status === 200 && resp && resp.data && resp.data.user_id) {
                            cb(resp.data.user_id);
                        } else {
                            cb(null);
                        }
                    });
                } else {
                    cb(null);
                }
            });
        } else {
            cb(null);
        }
    });
}

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

