"use strict";
/**
 * Copyright © 2018 Emu Analytics
 */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = exports.builder = exports.desc = exports.command = void 0;
const utils_1 = require("../../utils");
exports.command = ['metadata <email>', 'meta'];
exports.desc = 'Get/set resource metadata';
const builder = (args) => {
    return args
        .positional('email', { describe: 'User email (or unique prefix)', type: 'string' })
        .option('set', {
        type: 'array',
        describe: 'One or more key/values to set in form <key>=<value>. Use <key>= to delete a key.'
    });
};
exports.builder = builder;
function handler({ client, email, set }) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            if (!set) {
                // Get metadata
                const resource = yield (0, utils_1.resolveResource)(email, client.auth.users, 'email');
                (0, utils_1.logObject)(resource.metadata, 'json');
            }
            else {
                // Set metadata
                let resource = yield (0, utils_1.resolveResource)(email, client.auth.users, 'email');
                // Update metadata
                const keyValues = (0, utils_1.getMetadataKeyValues)(set);
                for (const key of Object.keys(keyValues)) {
                    const value = keyValues[key];
                    if (value === '') {
                        yield client.auth.users.deleteMetadata(resource.id, key);
                    }
                    else {
                        yield client.auth.users.setMetadata(resource.id, key, value);
                    }
                }
                // Reload
                resource = yield (0, utils_1.resolveResource)(email, client.auth.users, 'email');
                (0, utils_1.logObject)(resource.metadata, 'json');
            }
        }
        catch (e) {
            (0, utils_1.logError)(e);
        }
    });
}
exports.handler = handler;
//# sourceMappingURL=metadata.js.map