import { noop, logger } from "../utils";

// options: { command, params ?, callback }
// command: "pluginName.apiName"
// We abstract the access to the plugins in case of API or design changes,
// clients don't have to change their implementations, or update their Launch extensions.

const makeCommand = plugins => ({ command, params = {}, callback = noop } = {}) => {
    if (!command || command.indexOf(".") === -1) {
        throw new Error("[OptIn.execute] Please provide a valid command.");
    }

    try {
        const parts = command.split(".");
        const plugin = plugins[parts[0]];
        const apiName = parts[1];

        if (!plugin || typeof plugin[apiName] !== "function") {
            throw new Error("Make sure the plugin and API name exist.");
        }

        const args = Object.assign(params, { callback });
        plugin[apiName].call(plugin, args);

    } catch(ex) {
        logger.error("[execute] Something went wrong: " + ex.message);
    }
};

export default makeCommand;
