var Backend = (function(){
    
    const req = require('request');
    const crypto = require('crypto');
    
    //const base_url = "http://localhost:8080";
    const base_url = "http://ist-srv.welogy.net";
    const api_url_path = "/hub/api";
    const sig_algo = "sha256";

    const accept_formats = {
        "json":"application/json"
    }

    const apis = {
        'session':{
            'endpoints':{
                'progress':{
                    'url':base_url+'/'+api_url_path+'/session/progress',
                    'input':"domain=:domain"
                }
            },
            'passkey':'cc78112b8c6cfcb49cac8d4e43ce38c99bb018c2691ac5c9c29c64ea3ccdf32d',
            'domain':'fiu.edu',
            'version':'1.0',
            'stability':'dev'
        }
    };

    const req_headers = {
        'Auth-Api-Domain':null,
        'Auth-Api-Signature':null,
        'Accept':null
    };

    const api_auth = {
        'username':'fiu',
        'password':'fiumeetings',
    }

    return {
        session:{
            progress: function(domain, resolve, reject){

                // Holds request query params
                var req_params = apis.session.endpoints.progress.input.replace(":domain", domain);

                // Holds signature
                var signature = crypto.createHmac('sha256', apis.session.passkey).update(req_params).digest('hex');

                // Set headers
                req_headers["Auth-Api-Domain"] = apis.session.domain;
                req_headers["Auth-Api-Signature"] = signature;
                req_headers["Accept"] = "application/json;version="+apis.session.version+";stability="+apis.session.stability+";timestamp="+Math.floor(Date.now()/1000);

                req.get({
                    'url':apis.session.endpoints.progress.url+'?'+req_params,
                    'headers':req_headers,
                    'auth':{
                        'user':api_auth.username,
                        'pass':api_auth.password,
                        'sendImmediately':true
                    }
                },function(error, response, body){
                    if ((!error) && (response.statusCode == 200)){
                        resolve(body);
                    }
                    else{
                        reject(body);
                    }
                });
            }
        }
    }
})();

module.exports = Backend;




