'use strict';

require('babel-polyfill');

var _edgegrid = require('edgegrid');

var _edgegrid2 = _interopRequireDefault(_edgegrid);

var _dotenv = require('dotenv');

var _dotenv2 = _interopRequireDefault(_dotenv);

var _inquirer = require('inquirer');

var _inquirer2 = _interopRequireDefault(_inquirer);

var _formatJson = require('format-json');

var _formatJson2 = _interopRequireDefault(_formatJson);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
    var papiChoice = function () {
        var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(message, papiUrl, containerField, valueField, nameField) {
            var choices;
            return regeneratorRuntime.wrap(function _callee$(_context) {
                while (1) {
                    switch (_context.prev = _context.next) {
                        case 0:
                            _context.next = 2;
                            return callPapi(containerField, papiUrl).then(function (data) {
                                return data[containerField].items.map(function (item) {
                                    var choice = {};
                                    choice.name = item[valueField] + ' ' + item[nameField];
                                    choice.value = item[valueField];
                                    return choice;
                                });
                            });

                        case 2:
                            choices = _context.sent;
                            _context.next = 5;
                            return _inquirer2.default.prompt([{
                                type: 'list',
                                name: valueField,
                                message: message,
                                paginated: true,
                                choices: choices
                            }]).then(function (answers) {
                                console.log('selected ' + valueField + ' = ' + answers[valueField]);
                                return answers[valueField];
                            });

                        case 5:
                            return _context.abrupt('return', _context.sent);

                        case 6:
                        case 'end':
                            return _context.stop();
                    }
                }
            }, _callee, this);
        }));

        return function papiChoice(_x, _x2, _x3, _x4, _x5) {
            return _ref2.apply(this, arguments);
        };
    }();

    var callPapi = function () {
        var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(type, papiUrl) {
            return regeneratorRuntime.wrap(function _callee2$(_context2) {
                while (1) {
                    switch (_context2.prev = _context2.next) {
                        case 0:
                            return _context2.abrupt('return', new Promise(function (resolve, reject) {
                                console.log('calling papi url: ' + papiUrl + '\n');

                                edgegrid.auth({
                                    path: papiUrl,
                                    method: 'GET'
                                }).send(function (error, response, body) {
                                    if (error) {
                                        return reject(error);
                                    }
                                    var jsonResult = JSON.parse(body);
                                    papiResponses.set(type, jsonResult);
                                    return resolve(jsonResult);
                                });
                            }));

                        case 1:
                        case 'end':
                            return _context2.stop();
                    }
                }
            }, _callee2, this);
        }));

        return function callPapi(_x6, _x7) {
            return _ref3.apply(this, arguments);
        };
    }();

    var papiResponses, edgegrid, contractId, groupId, propertyId, latestVersion, version, propertyJson, propertyName;
    return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
            switch (_context3.prev = _context3.next) {
                case 0:

                    // load .env vars
                    _dotenv2.default.config();

                    papiResponses = new Map();
                    edgegrid = new _edgegrid2.default({
                        path: process.env.AKA_EDGERC,
                        section: 'default'
                    });
                    _context3.next = 5;
                    return papiChoice('Select Akamai contract:', '/papi/v1/contracts', 'contracts', 'contractId', 'contractTypeName');

                case 5:
                    contractId = _context3.sent;
                    _context3.next = 8;
                    return papiChoice('Select Akamai property group:', '/papi/v1/groups/?contractId=' + contractId, 'groups', 'groupId', 'groupName');

                case 8:
                    groupId = _context3.sent;
                    _context3.next = 11;
                    return papiChoice('Select Akamai property:', '/papi/v1/properties/?contractId=' + contractId + '&groupId=' + groupId, 'properties', 'propertyId', 'propertyName');

                case 11:
                    propertyId = _context3.sent;
                    latestVersion = papiResponses.get('properties').properties.items.filter(function (property) {
                        return property.propertyId === propertyId;
                    })[0].latestVersion;

                    // request property version

                    _context3.next = 15;
                    return _inquirer2.default.prompt([{
                        type: 'input',
                        name: 'version',
                        message: 'The latest property verions is ' + latestVersion + ', which would you like?',
                        default: latestVersion,
                        validate: function validate(version) {
                            if (parseInt(version) > 0 && parseInt(version) <= latestVersion) {
                                return true;
                            } else {
                                return 'Please enter a valid version number.';
                            }
                        }

                    }]).then(function (answers) {
                        console.log('selected version = ' + answers.version);
                        return answers.version;
                    });

                case 15:
                    version = _context3.sent;
                    _context3.next = 18;
                    return callPapi('property', '/papi/v1/properties/' + propertyId + '/versions/' + version + '/rules?contractId=' + contractId + '&groupId=' + groupId).then(function (data) {
                        return data;
                    });

                case 18:
                    propertyJson = _context3.sent;
                    propertyName = papiResponses.get('properties').properties.items.filter(function (property) {
                        return property.propertyId === propertyId;
                    })[0].propertyName;
                    _context3.next = 22;
                    return _inquirer2.default.prompt([{
                        type: 'confirm',
                        name: 'outputToFile',
                        message: 'Output property ' + propertyName + ' v' + version + ' json to file now?',
                        default: true

                    }]).then(function (answers) {
                        console.log('selected outputToFile = ' + answers.outputToFile);
                        if (answers.outputToFile) {
                            var outputDir = __dirname + '/../papiJson';
                            if (!_fs2.default.existsSync(outputDir)) {
                                _fs2.default.mkdirSync(outputDir);
                            }
                            _fs2.default.writeFileSync(outputDir + '/' + propertyName + '-v' + version + '.papi.json', _formatJson2.default.plain(propertyJson), 'utf8');
                            console.log('\npapi json written to: ./papiJson/' + propertyName + '-v' + version + '.papi.json');
                        }
                    });

                case 22:

                    console.log('\n# ---------------------------------------------------------\n' + '# place the following in .env or set as shell/node env vars\n' + '# if you would like to use these parameters to configure nginx directly\n' + '# from api calls - otherwise point at the generated papi json.\n' + '# refer to start.js and start-local.js\n' + 'AKA_CONTRACT_ID=' + contractId + '\n' + 'AKA_GROUP_ID=' + groupId + '\n' + 'AKA_PROPERTY_ID=' + propertyId + '\n' + 'AKA_PROPERTY_VERSION=' + version + '\n');

                case 23:
                case 'end':
                    return _context3.stop();
            }
        }
    }, _callee3, this);
}))();