/*
 * Copyright (c) Contributors to the Open 3D Engine Project.
 * For complete copyright and license terms please see the LICENSE at the root of this distribution.
 *
 * SPDX-License-Identifier: Apache-2.0 OR MIT
 *
 */
var http = require("https");

var amznClientID = "{{amznClientID}}";
var amznClientSecret = "{{amznClientSecret}}";
var amznRedirectUrl = "{{amznRedirectUrl}}";

var getAmazonRefreshToken = function(code,  callback)
{
    var options = {
        hostname: 'api.amazon.com',
        path: '/auth/o2/token',
        port: 443,
        method : "POST",
        headers  : {'Content-Type':     'application/x-www-form-urlencoded;charset=UTF-8'}
        };

    var body = "grant_type=authorization_code&";
    body += "code=" + code + "&";
    body += "client_id=" + amznClientID + "&";
    body += "client_secret=" + amznClientSecret + "&";
    body += "redirect_uri=" + amznRedirectUrl;
    console.log(body);
    var req = http.request(options, function(res) {

        res.setEncoding('utf8');
        var store = "";

        res.on('data', function (chunk) {
            console.log(chunk);
            store += chunk;
        });

        res.on('end', function() {
            var response = JSON.parse(store);
            var data = {
                access_token : response.access_token,
                expires_in : response.expires_in,
                refresh_token : response.refresh_token,

                };
                console.log(data);
            callback(null, data);

        });

        req.on('error', function(e) {
            console.log('problem with request: ' + e.message);
            callback(e);
        });
    });

    req.write(body);
    req.end();

};

var refreshAccessToken = function(refreshToken,  callback)
{
    var options = {
        hostname: 'api.amazon.com',
        path: '/auth/o2/token',
        port: 443,
        method : "POST",
        headers  : {'Content-Type':     'application/x-www-form-urlencoded;charset=UTF-8'}
        };

    var body = "grant_type=refresh_token&";
    body += "refresh_token=" + refreshToken + "&";
    body += "client_id=" + amznClientID + "&";
    body += "client_secret=" + amznClientSecret;
    console.log(body);
    var req = http.request(options, function(res) {

        res.setEncoding('utf8');
        var store = "";

        res.on('data', function (chunk) {
            console.log(chunk);
            store += chunk;
        });

        res.on('end', function() {
            var response = JSON.parse(store);
            var data = {
                access_token : response.access_token,
                expires_in : response.expires_in,
                refresh_token : response.refresh_token,

                };
                console.log(data);
            callback(null, data);

        });

        req.on('error', function(e) {
            console.log('problem with request: ' + e.message);
            callback(e);
        });
    });

    req.write(body);
    req.end();

};

exports.{{handlerName}} = function(event, context) {
    if(typeof event.code != 'undefined') {
        var code = event.code;
        console.log(code);

        getAmazonRefreshToken(code, function(err, data)
        {
            if(err)
            {
                context.fail(err);
            }
            else
            {

                context.succeed (data);

            }
        });
    }
    else if(typeof event.refresh_token != 'undefined') {
        var refresh_token = event.refresh_token;
        console.log(refresh_token);

        refreshAccessToken(refresh_token, function(err, data)
        {
            if(err)
            {
                context.fail(err);
            }
            else
            {
                context.succeed (data);
            }
        });
    }
};
