"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Emitter_1 = __importDefault(require("../Emitter"));
var bluebird_1 = __importDefault(require("bluebird"));
var Helpers_1 = __importDefault(require("../Helpers"));
var helpers = new Helpers_1.default();
// Main/public page service
var api;
var RangesWrap = /** @class */ (function () {
    function RangesWrap(ippApi) {
        api = ippApi;
    }
    return RangesWrap;
}());
exports.RangesWrap = RangesWrap;
var PermissionRange = /** @class */ (function () {
    function PermissionRange(name, rowStart, rowEnd, colStart, colEnd, permissions) {
        if (rowStart === void 0) { rowStart = 0; }
        if (rowEnd === void 0) { rowEnd = 0; }
        if (colStart === void 0) { colStart = 0; }
        if (colEnd === void 0) { colEnd = 0; }
        this.name = name;
        this.rowStart = rowStart;
        this.rowEnd = rowEnd;
        this.colStart = colStart;
        this.colEnd = colEnd;
        // @todo Constants for permissions ro, no etc
        this._permissions = {
            ro: [],
            no: []
        };
        if (permissions) {
            this._permissions = permissions;
        }
    }
    PermissionRange.prototype.getCellsReference = function () {
        return helpers.getCellsReference({ row: this.rowStart, col: this.colStart }, { row: this.rowEnd, col: this.colEnd });
    };
    PermissionRange.prototype.setCellsReference = function (ref, rows, cols) {
        var cellRange = helpers.cellRange(ref, rows, cols);
        this.rowStart = cellRange.from.row;
        this.colStart = cellRange.from.col;
        this.rowEnd = cellRange.to.row;
        this.colEnd = cellRange.to.col;
    };
    /**
     * Set permission for a user
     * @param userId
     * @param permission
     */
    PermissionRange.prototype.setPermission = function (userId, permission) {
        if (permission) {
            permission = permission.toLowerCase();
        }
        if (['ro', 'no'].indexOf("" + permission) < 0) {
            permission = null;
        }
        // First remove user rom all ranges
        if (this._permissions.ro.indexOf(userId) >= 0) {
            this._permissions.ro.splice(this._permissions.ro.indexOf(userId), 1);
        }
        if (this._permissions.no.indexOf(userId) >= 0) {
            this._permissions.no.splice(this._permissions.no.indexOf(userId), 1);
        }
        if (permission) {
            this._permissions[permission].push(userId);
        }
    };
    PermissionRange.prototype.togglePermission = function (userId, currentPermission) {
        if (currentPermission === 'ro') {
            currentPermission = 'no';
        }
        else if (currentPermission === 'no') {
            currentPermission = null;
        }
        else {
            currentPermission = 'ro';
        }
        this.setPermission(userId, currentPermission);
        return this.getPermission(userId);
    };
    /**
     * Get permission for a user
     * @param userId
     * @returns {string}
     */
    PermissionRange.prototype.getPermission = function (userId) {
        var permission = '';
        if (this._permissions.ro.indexOf(userId) >= 0) {
            permission = 'ro';
        }
        else if (this._permissions.no.indexOf(userId) >= 0) {
            permission = 'no';
        }
        return permission || 'rw';
    };
    /**
     * Serialize range to final service-accepted object
     * @returns {{name: string, start: string, end: string, rights: IPageRangeRights, freeze: boolean}}
     */
    PermissionRange.prototype.toObject = function () {
        return {
            name: this.name,
            start: this.rowStart + ":" + this.colStart,
            end: this.rowEnd + ":" + this.colEnd,
            rights: this._permissions,
            freeze: false,
            button: false,
            style: false,
            access: false,
            notification: false,
            list: false
        };
    };
    return PermissionRange;
}());
exports.PermissionRange = PermissionRange;
var PermissionRangeWrap = /** @class */ (function () {
    function PermissionRangeWrap() {
        return PermissionRange;
    }
    return PermissionRangeWrap;
}());
exports.PermissionRangeWrap = PermissionRangeWrap;
var Ranges = /** @class */ (function (_super) {
    __extends(Ranges, _super);
    function Ranges(folderId, pageId, pageAccessRights) {
        var _this = _super.call(this) || this;
        /**
         * List of ranges in collection
         * @type {Array}
         * @private
         */
        _this._ranges = [];
        _this._folderId = folderId;
        _this._pageId = pageId;
        if (pageAccessRights) {
            _this.parse(pageAccessRights);
        }
        return _this;
    }
    Object.defineProperty(Ranges.prototype, "TYPE_PERMISSION_RANGE", {
        get: function () {
            return 'permissions';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Ranges.prototype, "TYPE_FREEZING_RANGE", {
        get: function () {
            return 'freezing';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Ranges.prototype, "EVENT_UPDATED", {
        get: function () {
            return 'updated';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Ranges.prototype, "ranges", {
        /**
         * Getter for list of ranges
         * @returns {IPageRangeItem[]}
         */
        get: function () {
            return this._ranges;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Rewrites current collection of ranges with given ranges
     * @param ranges
     * @returns {ipushpull.Ranges}
     */
    Ranges.prototype.setRanges = function (ranges) {
        this._ranges = ranges;
        return this;
    };
    /**
     * Adds range to collection. Also prevents duplicate names
     * @param range
     * @returns {ipushpull.Ranges}
     */
    Ranges.prototype.addRange = function (range) {
        // Prevent duplicates
        var nameUnique = false;
        var newName = range.name;
        var count = 1;
        while (!nameUnique) {
            nameUnique = true;
            for (var i = 0; i < this._ranges.length; i++) {
                if (this._ranges[i].name === newName) {
                    nameUnique = false;
                    newName = range.name + '_' + count;
                    count++;
                }
            }
        }
        range.name = newName;
        this._ranges.push(range);
        return this;
    };
    /**
     * Removes range from collection
     *
     * @param rangeName
     * @returns {ipushpull.Ranges}
     */
    Ranges.prototype.removeRange = function (rangeName) {
        var index = -1;
        for (var i = 0; i < this._ranges.length; i++) {
            if (this._ranges[i].name === rangeName) {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            this._ranges.splice(index, 1);
        }
        return this;
    };
    /**
     * Save ranges to a page
     * @returns {Promise<IRequestResult>}
     */
    // @todo This is way out of scope
    Ranges.prototype.save = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var ranges = [];
            // Convert all ranges to objects
            for (var i = 0; i < _this._ranges.length; i++) {
                ranges.push(_this._ranges[i].toObject());
            }
            var requestData = {
                domainId: _this._folderId,
                pageId: _this._pageId,
                data: {
                    range_access: ranges.length ? JSON.stringify(ranges) : ''
                }
            };
            api.savePageSettings(requestData).then(function (data) {
                _this.emit(_this.EVENT_UPDATED);
                resolve(data);
            }, reject);
        });
        return p;
    };
    /**
     * Parse range data loaded from service into range collection
     * @param pageAccessRights
     * @returns {IPageRangeItem[]}
     */
    Ranges.prototype.parse = function (pageAccessRights) {
        var ar = JSON.parse(pageAccessRights);
        this._ranges = [];
        for (var i = 0; i < ar.length; i++) {
            var range = {
                from: {
                    row: parseInt(ar[i].start.split(':')[0], 10),
                    col: parseInt(ar[i].start.split(':')[1], 10)
                },
                to: {
                    row: parseInt(ar[i].end.split(':')[0], 10),
                    col: parseInt(ar[i].end.split(':')[1], 10)
                }
            };
            this._ranges.push(new PermissionRange(ar[i].name, range.from.row, range.to.row, range.from.col, range.to.col, ar[i].rights));
        }
        return this._ranges;
    };
    return Ranges;
}(Emitter_1.default));
exports.Ranges = Ranges;
//# sourceMappingURL=Range.js.map