"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Buttons_1 = require("./Buttons");
var Styles_1 = require("./Styles");
var Tasks_1 = require("./Tasks");
var Emitter_1 = __importDefault(require("../Emitter"));
var bluebird_1 = __importDefault(require("bluebird"));
var Helpers_1 = __importDefault(require("../Helpers"));
var helpers = new Helpers_1.default();
var Actions = /** @class */ (function (_super) {
    __extends(Actions, _super);
    // public Content: IPageContentProvider;
    // public Functions: IFunctions;
    function Actions(api, Content, Functions, folderId, pageId) {
        var _this = _super.call(this) || this;
        _this.api = api;
        _this.Content = Content;
        _this.Functions = Functions;
        _this.folderId = folderId;
        _this.pageId = pageId;
        _this.buttons = [];
        _this.styles = [];
        _this.tasks = [];
        _this.states = [];
        _this.freeze = {
            row: 0,
            col: 0,
        };
        _this.charts = [];
        _this.filters = {
            enabled: false,
        };
        _this.config = {
            states_menu: "",
        };
        return _this;
    }
    Object.defineProperty(Actions.prototype, "EVENT_UPDATED", {
        get: function () {
            return "updated";
        },
        enumerable: true,
        configurable: true
    });
    Actions.prototype.parse = function (str) {
        var _this = this;
        this.reset();
        var actions = str ? JSON.parse(str) : {};
        [
            "buttons",
            "styles",
            "tasks",
            "freeze",
            "states",
            "charts",
            "filters",
            "config",
        ].forEach(function (key) {
            if (!actions[key])
                return;
            if (key === "buttons") {
                // this.buttons = [];
                actions[key].forEach(function (buttonData) {
                    _this.buttons.push(new Buttons_1.Button(buttonData));
                });
            }
            else if (key === "styles") {
                // this.styles = [];
                actions[key].forEach(function (data) {
                    _this.styles.push(new Styles_1.Style(data));
                });
            }
            else if (key === "tasks") {
                // this.tasks = [];
                actions[key].forEach(function (taskData) {
                    _this.tasks.push(new Tasks_1.Task(taskData));
                });
            }
            else if (key === "config") {
                _this.config = __assign({}, _this.config, actions[key]);
            }
            else {
                _this[key] = actions[key];
            }
        });
    };
    Actions.prototype.toString = function () {
        return JSON.stringify({
            buttons: this.buttons,
            styles: this.styles,
            tasks: this.tasks,
            freeze: this.freeze,
            states: this.states,
            charts: this.charts,
            filters: this.filters,
            config: this.config,
        });
    };
    Actions.prototype.save = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var requestData = {
                domainId: _this.folderId,
                pageId: _this.pageId,
                data: {
                    action_definitions: _this.toString(),
                },
            };
            _this.api.savePageSettings(requestData).then(function (data) {
                // this.emit(this.EVENT_UPDATED);
                resolve(data);
            }, reject);
        });
        return p;
    };
    Actions.prototype.run = function (gridCell, canEdit) {
        var _this = this;
        var run = {
            cellUpdates: [],
            notifications: [],
            shares: [],
            styles: [],
            components: [],
            values: [],
        };
        var notificationIds = [];
        this.tasks.forEach(function (taskGroup) {
            if (!_this.Functions.isButtonWithinTaskRange(gridCell, taskGroup)) {
                return;
            }
            taskGroup.tasks.forEach(function (task, taskIndex) {
                var cell = _this.Content.getCell(gridCell.row, gridCell.col);
                _this.Functions.setCellReference(cell);
                if (!_this.Functions.isTaskValid(task))
                    return;
                task.actions.forEach(function (action, actionIndex) {
                    var cell = _this.Content.getCell(gridCell.row, gridCell.col);
                    _this.Functions.setCellReference(cell);
                    switch (action.type) {
                        case "component":
                            run.components.push(new Tasks_1.ComponentTaskAction({
                                data: _this.Functions.parse(action.component.data),
                                type: action.component.type,
                                name: action.component.name,
                            }));
                            break;
                        // case 'javascript':
                        //   eval(action.javascript.code);
                        //   break;
                        case "copy":
                            var value = _this.Functions.parse(action.data.value);
                            run.values.push("" + value);
                            break;
                        case "value":
                            var cellUpdate = _this.Functions.updateCell(action);
                            if (cellUpdate && canEdit) {
                                _this.Content.updateCell(cellUpdate.row, cellUpdate.col, cellUpdate.data);
                                if (!run.cellUpdates[cellUpdate.row])
                                    run.cellUpdates[cellUpdate.row] = [];
                                run.cellUpdates[cellUpdate.row][cellUpdate.col] = _this.Content.getCell(cellUpdate.row, cellUpdate.col);
                                _this.Functions.updateContentDelta(run.cellUpdates);
                            }
                            break;
                        case "share":
                            run.shares.push(new Tasks_1.ShareTaskAction({
                                title: _this.Functions.parse(action.share.title),
                                subTitle: _this.Functions.parse(action.share.subTitle),
                                blurb: _this.Functions.parse(action.share.blurb),
                            }));
                            break;
                        case "notification":
                            var data_1 = {
                                type: action.notification.type,
                                send_to: action.notification.send_to,
                                allow_custom_text: action.notification.allow_custom_text,
                                message: _this.Functions.parse(action.notification.message, "<br />"),
                                body: _this.Functions.parse(action.notification.body, "<br />"),
                                destinations: {
                                    "symphony-obo": []
                                },
                                notification_destinations: []
                            };
                            if (action.notification.destinations instanceof Array) {
                                action.notification.destinations.forEach(function (destination) {
                                    if (typeof destination == 'string')
                                        data_1.destinations['symphony-obo'].push(destination);
                                    else
                                        data_1.notification_destinations.push(destination);
                                });
                            }
                            var messageNotification = new Tasks_1.NotificationTaskAction(data_1);
                            var key = "n-" + gridCell.row + "-" + gridCell.col + "-" + taskIndex + "-" + actionIndex;
                            if (notificationIds.indexOf(key) < 0) {
                                notificationIds.push(key);
                                run.notifications.push(messageNotification);
                            }
                            break;
                    }
                });
            });
        });
        run.styles = this.Functions.getCellFormatting(this.styles, this.buttons);
        return run;
    };
    Actions.prototype.reset = function () {
        this.buttons = [];
        this.styles = [];
        this.tasks = [];
        this.config.states_menu = '';
        this.charts = [];
        this.freeze.col = 0;
        this.freeze.row = 0;
        this.filters.enabled = false;
    };
    /**
     *
     * @param messageNotification
     * @param options
     *
     */
    Actions.prototype.sendNotification = function (messageNotification, options) {
        var _this = this;
        var message = "";
        var icon = options && options.icon ? options.icon : "";
        if (messageNotification.type === "card") {
            message = "<card iconSrc=\"" + icon + "\" accent=\"tempo-bg-color--blue\"><header>" + helpers.safeXmlChars(messageNotification.message) + "</header><body>" + helpers.safeXmlChars(messageNotification.body) + "</body></card>";
        }
        else {
            message = helpers.safeXmlChars(messageNotification.message);
        }
        var type = messageNotification.conversation_id
            ? "symphony-obo"
            : "";
        var data = {
            destinations: messageNotification.destinations,
            notification_destinations: messageNotification.notification_destinations,
            message: message,
        };
        if (type) {
            data.type = type;
        }
        // TODO: move to a list of 'destinations'
        if (messageNotification.conversation_id) {
            data.symphony_conversation_id = messageNotification.conversation_id;
        }
        // if (messageNotification.destinations) {
        //   data.notification_destinations = messageNotification.destinations;
        // }
        var create = options && options.write_access
            ? "createPageNotification"
            : "createNotification";
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.api[create]({
                pageId: _this.pageId,
                data: data,
            })
                .then(function () {
                resolve(true);
            })
                .catch(function (err) {
                var message = "Unable to send message. Notification bot or Conversation ID not found";
                try {
                    if (err.code < 500) {
                        var data_2 = JSON.parse(err.error);
                        message = data_2.message;
                    }
                }
                catch (e) { }
                reject(message);
            });
        });
        return p;
    };
    Actions.prototype.validateButton = function (button, buttonIndex) {
        var errors = [];
        if (!button.name) {
            errors.push("Name is missing");
        }
        if (!button.range) {
            errors.push("Cell Range is missing");
        }
        if (!button.options.length &&
            ["rotate", "select"].indexOf(button.type) > -1) {
            errors.push("Type Options are missing");
        }
        this.buttons.forEach(function (existingButton, index) {
            if (index == buttonIndex)
                return;
            if (existingButton.name === button.name) {
                errors.push("Name already exists");
            }
        });
        return errors;
    };
    Actions.prototype.addButton = function (button) {
        this.buttons.forEach(function (b, index) {
            if (button.name !== b.name)
                return;
            button.name = button.name + "_" + index;
        });
        this.buttons.push(button);
        this.emit(this.EVENT_UPDATED);
        return this.buttons;
    };
    Actions.prototype.addChart = function (chart) {
        this.charts.forEach(function (b, index) {
            if (chart.name !== b.name)
                return;
            chart.name = chart.name + "_" + index;
        });
        this.charts.push(chart);
        return this.charts;
    };
    Actions.prototype.addState = function (state) {
        this.states.forEach(function (s, index) {
            if (state.name !== s.name)
                return;
            state.name = state.name + "_" + index;
        });
        this.states.push(state);
        return this.states;
    };
    Actions.prototype.addStyle = function (style) {
        this.styles.push(style);
        this.emit(this.EVENT_UPDATED);
        return this.styles;
    };
    Actions.prototype.addTask = function (task) {
        this.tasks.push(task);
        this.emit(this.EVENT_UPDATED);
        return this.tasks;
    };
    Actions.prototype.removeButton = function (name) {
        var _this = this;
        this.buttons.forEach(function (button, index) {
            if (button.name !== name)
                return;
            _this.buttons.splice(index, 1);
        });
        this.emit(this.EVENT_UPDATED);
    };
    Actions.prototype.removeState = function (name) {
        var _this = this;
        this.states.forEach(function (state, index) {
            if (state.name !== name)
                return;
            _this.states.splice(index, 1);
        });
        this.emit(this.EVENT_UPDATED);
    };
    Actions.prototype.removeStyle = function (name) {
        var _this = this;
        this.styles.forEach(function (style, index) {
            if (style.ref !== name && style.range !== name)
                return;
            _this.styles.splice(index, 1);
        });
        this.emit(this.EVENT_UPDATED);
    };
    Actions.prototype.removeTask = function (name) {
        var _this = this;
        this.tasks.forEach(function (task, index) {
            if (task.ref !== name && task.range !== name)
                return;
            _this.tasks.splice(index, 1);
        });
        this.emit(this.EVENT_UPDATED);
    };
    Actions.prototype.removeChart = function (name) {
        var _this = this;
        this.charts.forEach(function (chart, index) {
            if (chart.name !== name)
                return;
            _this.charts.splice(index, 1);
        });
    };
    return Actions;
}(Emitter_1.default));
exports.Actions = Actions;
//# sourceMappingURL=Actions.js.map