"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 Helpers_1 = __importDefault(require("../Helpers"));
var Emitter_1 = __importDefault(require("../Emitter"));
var helpers = new Helpers_1.default();
var GridCell = /** @class */ (function (_super) {
    __extends(GridCell, _super);
    function GridCell(Page, Events, row, col) {
        var _this = _super.call(this) || this;
        _this.Page = Page;
        _this.Events = Events;
        _this.row = row;
        _this.col = col;
        // public Page!: IGridPage;
        // public Events!: IGridEvents;
        _this.type = 'cell';
        _this.created = false;
        _this.initialized = false;
        _this.selected = false;
        _this.found = false;
        _this.dataset = {
            x: 0,
            y: 0,
            width: 0,
            height: 0,
            overflow: 0,
            row: 0,
            col: 0
        };
        _this.button = null;
        _this.link = null;
        _this.style = null;
        _this.reference = '';
        _this.checked = false;
        _this.hasHistory = false;
        _this.isButton = false;
        _this.hasButtonOptions = false;
        _this.canEditButton = false;
        _this.isImage = false;
        _this.hidden = false;
        _this.permission = 'rw';
        _this.position = {
            row: -1,
            col: -1
        };
        _this.index = {
            row: -1,
            col: -1
        };
        _this.editing = false;
        _this.borders = {
            widths: {
                none: 0,
                thin: 1,
                medium: 2,
                thick: 3
            },
            styles: {
                none: 'none',
                solid: 'solid',
                double: 'double',
                dash: 'dashed'
            },
            names: {
                t: 'top',
                r: 'right',
                b: 'bottom',
                l: 'left'
            }
        };
        _this.cellStyles = [
            'background-color',
            'color',
            'font-family',
            'font-size',
            'font-style',
            'font-weight',
            'height',
            'text-align',
            'text-wrap',
            'width',
            'vertical-align'
        ];
        _this.highlightTimer = null;
        _this.oldValue = '';
        _this._rowIndex = 0;
        _this.selectedOption = 0;
        _this.done = false;
        _this.historyUser = -1;
        _this.mergedCells = [];
        _this.mergeWidth = 0;
        _this._sticky = false;
        _this.onWindowClick = function (evt) {
            var isPopper = helpers.isTarget(evt.target, _this.cellPopper);
            var isCell = helpers.isTarget(evt.target, _this.cell);
            if (isPopper || isCell)
                return;
            _this.destroyPopper();
        };
        _this.init(row, col);
        return _this;
    }
    Object.defineProperty(GridCell.prototype, "rowIndex", {
        get: function () {
            return this._rowIndex;
        },
        set: function (n) {
            this._rowIndex = n;
            this.index.row = n;
            if (this.created)
                this.cell.dataset.rowIndex = "" + this.rowIndex;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GridCell.prototype, "sticky", {
        get: function () {
            return this._sticky;
        },
        set: function (n) {
            this._sticky = n;
            if (n) {
                this.cell.classList.add('sticky');
            }
            else {
                this.cell.classList.remove('sticky');
            }
        },
        enumerable: true,
        configurable: true
    });
    GridCell.prototype.create = function () {
        if (this.created)
            return;
        this.created = true;
        // main cell
        this.cell = document.createElement('div');
        this.cell.classList.add('grid-cell');
        this.cell.classList.add("grid-col-" + this.col);
        this.cell.dataset.row = "" + this.row;
        this.cell.dataset.col = "" + this.col;
        this.cell.dataset.rowIndex = "" + this.rowIndex;
        this.cell.style.setProperty('z-index', "" + (this.Page.cols - this.col));
        // background
        this.cellBackground = document.createElement('div');
        this.cellBackground.className = 'grid-background';
        this.cell.appendChild(this.cellBackground);
        // borders
        this.cellBorders = document.createElement('div');
        this.cellBorders.className = 'grid-border';
        // text
        this.cellTextContainer = document.createElement('div');
        this.cellTextContainer.className = 'grid-text';
        this.cellText = document.createElement('div');
        this.cellTextContainer.appendChild(this.cellText);
    };
    GridCell.prototype.setData = function () {
        var pos = this.Page.cellPos(this.row, this.col);
        this.dataset.x = pos.x;
        this.dataset.y = pos.y;
        this.dataset.width = parseFloat(this.content.style.width);
        this.dataset.overflow = parseFloat(this.content.style.width);
        this.dataset.height = parseFloat(this.content.style.height);
    };
    GridCell.prototype.init = function (row, col) {
        var content = __assign({ value: '', formatted_value: '', style: {} }, this.Page.originalContent[row][col]);
        this.content = content;
        this.rowIndex = row;
        this.index.row = this.row;
        this.index.col = this.col;
        this.position = this.content.index;
        this.row = row;
        this.col = col;
        this.reference = "" + helpers.toColumnName(this.col + 1) + (this.row + 1);
        this.setData();
    };
    GridCell.prototype.refresh = function () {
        if (!this.created)
            return;
        this.update(true);
    };
    GridCell.prototype.update = function (force) {
        var _this = this;
        var update = force || false;
        if (!this.created) {
            update = true;
            this.create();
        }
        if (this.Page.deltaContent[this.row] && this.Page.deltaContent[this.row][this.col]) {
            update = true;
            this.content = __assign({}, this.Page.deltaContent[this.row][this.col]);
            delete this.Page.deltaContent[this.row][this.col];
        }
        if (!update)
            return;
        this.setData();
        var style = __assign({}, this.content.style, this.style);
        if (style.background) {
            style['background-color'] = style.background;
        }
        // merge column def style
        if (!this.row && this.Page.columnsDefs[this.col] && this.Page.columnsDefs[this.col].style) {
            style = __assign({}, style, this.Page.columnsDefs[this.col].style);
        }
        var backgroundColor = ("#" + style['background-color']).replace('##', '#');
        var textColor = ("#" + style['color']).replace('##', '#');
        this.cellBackground.style.setProperty('background-color', backgroundColor);
        this.cell.classList.remove('light', 'dark');
        this.cell.classList.add(helpers.getContrastYIQ(backgroundColor));
        this.cell.classList.add("permission-" + this.permission);
        if (this.cellBackgroundHighlight) {
            this.cellBackgroundHighlight.style.setProperty('background-color', textColor);
        }
        if (("" + this.content.value).indexOf('data:image') > -1) {
            this.cell.classList.add("image");
            if (!this.cellImage) {
                this.cellImage = document.createElement('img');
            }
            this.cellImage.src = "" + this.content.value;
            this.cell.innerHTML = '';
            this.cell.appendChild(this.cellImage);
            this.isImage = true;
        }
        else {
            this.cell.classList.remove("image");
            if (this.cell.contains(this.cellImage)) {
                this.cell.removeChild(this.cellImage);
            }
            if (!this.found) {
                this.cell.classList.remove('cell-found');
            }
            else {
                this.cell.classList.add("cell-found");
            }
            this.history(this.hasHistory, this.historyUser);
            this.applyButton();
            this.applyBorders();
            this.applyText(false, textColor);
            var interval_1 = setInterval(function () {
                if (!_this.cell.parentNode)
                    return;
                clearInterval(interval_1);
                interval_1 = null;
                _this.applySoftMerge();
            }, 10);
        }
    };
    GridCell.prototype.getDetails = function () {
        return {
            content: this.content,
            row: this.row,
            col: this.col,
            position: {
                row: this.row,
                col: this.col
            },
            index: {
                row: this.content.index.row,
                col: this.content.index.col
            },
            dataset: __assign({}, this.dataset),
            reference: this.reference,
            link: this.content.link,
            button: this.button,
            history: this.hasHistory,
            checked: this.checked,
            sticky: this.sticky
        };
    };
    GridCell.prototype.getFlattenStyles = function (only) {
        var htmlStyle = {};
        var styles = this.content.style;
        if (this.style) {
            styles['background-color'] = this.style.background;
            styles.color = this.style.color;
        }
        this.cellStyles.forEach(function (s) {
            htmlStyle[s] = styles[s];
        });
        for (var key in this.borders.names) {
            var name_1 = this.borders.names[key];
            var width = this.borders.widths[styles[key + "bw"]] + 'px';
            var style = styles[key + "bs"];
            var color = '#' + styles[key + "bc"].replace('#', '');
            htmlStyle["border-" + name_1] = width + " " + style + " " + color;
        }
        var str = '';
        for (var attr in htmlStyle) {
            var value = htmlStyle[attr];
            if ((attr === 'background-color' || attr === 'color') && value.indexOf('#') === -1) {
                value = "#" + value;
            }
            if (only && only.length && only.indexOf(attr) < 0)
                continue;
            str += attr + ":" + value + ";";
        }
        return str;
    };
    GridCell.prototype.setFreeze = function (n) {
        // if (n === this.sticky) return;
        this.sticky = n;
        if (n) {
            // let left = this.Page.colWidths.slice(0, this.col).reduce((a: any, b: any) => a + b, 0);
            this.cell.classList.add('sticky');
            var offset = this.Page.headings ? 40 : 0;
            this.cell.style.setProperty('left', this.dataset.x + offset + "px");
        }
        else {
            this.cell.classList.remove('sticky');
            this.cell.style.removeProperty('left');
        }
    };
    GridCell.prototype.setSelected = function (selection) {
        this.selected = this.Page.selectedRows.includes(this.row) && this.Page.selectedCols.includes(this.col);
        // this.col >= selection.colFrom &&
        // this.row >= selection.rowFrom &&
        // this.col <= selection.colTo &&
        // this.row <= selection.rowTo;
        // if (n === this.selected) return;
        // console.log(this.selected, this.row, this.col);
        if (this.selected) {
            this.cell.classList.add('selected');
            if (this.col == selection.from.col && this.row == selection.from.row)
                this.cell.classList.add('selected-start');
            else
                this.cell.classList.remove('selected-start');
        }
        else {
            this.cell.classList.remove('selected', 'selected-start');
        }
    };
    GridCell.prototype.setButton = function (button) {
        this.button = button;
        this.refresh();
    };
    GridCell.prototype.setFound = function (n) {
        this.found = n;
        this.refresh();
    };
    GridCell.prototype.setStyle = function (style) {
        this.style = style;
        this.refresh();
    };
    GridCell.prototype.setPermission = function (permission) {
        if (this.content.column_name)
            permission = 'ro';
        this.permission = permission;
        this.refresh();
    };
    GridCell.prototype.setSorting = function (direction) {
        if (!direction) {
            this.cell.classList.remove('sorting-asc', 'sorting-desc');
        }
        else {
            this.cell.classList.add("sorting-" + direction);
        }
    };
    GridCell.prototype.highlight = function (show, hide) {
        var _this = this;
        if (show === void 0) { show = 0.5; }
        if (hide === void 0) { hide = 1; }
        if (this.highlightTimer) {
            clearTimeout(this.highlightTimer);
            this.highlightTimer = null;
        }
        if (!this.cellBackgroundHighlight) {
            this.cellBackgroundHighlight = document.createElement('div');
            this.cellBackgroundHighlight.className = 'grid-highlight';
            this.cellBackgroundHighlight.style.setProperty('background-color', "#" + this.content.style['color']);
            this.cellBackground.appendChild(this.cellBackgroundHighlight);
        }
        this.cellBackgroundHighlight.classList.remove('fade');
        this.cellBackgroundHighlight.classList.add('flash');
        this.highlightTimer = setTimeout(function () {
            // this.cellBackgroundHighlight.classList.remove('flash');
            _this.cellBackgroundHighlight.classList.add('fade');
        }, show * 1000);
    };
    GridCell.prototype.history = function (n, user) {
        var _a;
        if (user === void 0) { user = 0; }
        this.hasHistory = n;
        this.historyUser = user;
        if (!this.created)
            return;
        if (n) {
            if (!this.cellHistory) {
                this.cellHistory = document.createElement('div');
                this.cellHistory.className = 'grid-history';
                this.cell.appendChild(this.cellHistory);
            }
            this.cell.classList.add('history', "user-" + user);
        }
        else {
            var users = Array(10)
                .fill(1)
                .map(function (x, i) { return "user-" + i; });
            (_a = this.cell.classList).remove.apply(_a, ['history'].concat(users));
            if (this.cellHistory && this.cellHistory.parentNode) {
                this.cell.removeChild(this.cellHistory);
                this.cellHistory = null;
            }
        }
    };
    GridCell.prototype.cancel = function (restore) {
        // this.destroyPopper();
        console.log('cancel');
        if (restore) {
            this.cellText.textContent = this.oldValue;
            this.content.value = this.oldValue;
            this.content.formatted_value = this.oldValue;
        }
        if (this.input) {
            this.input.blur();
        }
    };
    GridCell.prototype.onButton = function () {
        if (!this.button || this.buttonPopper)
            return false;
        this.oldValue = "" + this.content.formatted_value || "" + this.content.value;
        if (this.button.type === 'checkbox') {
            this.toggleCheckbox();
            return true;
        }
        if (this.button.type === 'rotate') {
            var value = helpers.getNextValueInArray(this.content.formatted_value || this.content.value, this.button.options);
            this.cellText.textContent = this.content.formatted_value = this.content.value = value;
            // this.emit(this.editValue, value);
            // this.emit(this.DONE, value);
            // this.emit(this.STOP);
            this.Events.emit(this.Events.CELL, {
                cell: this,
                evt: {
                    type: 'blur'
                },
                done: true
            });
            return true;
        }
        return false;
    };
    GridCell.prototype.selectOption = function (key) {
        var dir = key.replace('Arrow', '').toLowerCase();
        if (!this.button || !this.hasButtonOptions)
            return false;
        if (dir === 'enter') {
            this.setSelectOption(key);
            return true;
        }
        else if (dir === 'down' || dir === 'right') {
            this.selectedOption++;
            if (this.selectedOption >= this.button.options.length) {
                this.selectedOption = 0;
            }
        }
        else {
            this.selectedOption--;
            if (this.selectedOption < 0) {
                this.selectedOption = this.button.options.length - 1;
            }
        }
        if (this.button.type === 'select') {
            this.updateSelectOptions();
        }
        else {
            this.setSelectOption();
        }
        return true;
    };
    GridCell.prototype.openOptions = function () {
        var _this = this;
        if (!this.button)
            return;
        this.button.options.forEach(function (option, index) {
            if (option !== _this.cellText.textContent)
                return;
            _this.selectedOption = index;
        });
        this.updateSelectOptions();
    };
    GridCell.prototype.toggleCheckbox = function (n) {
        this.checked = n === undefined ? !this.checked : n;
        this.content.checked = this.checked;
        var response = {
            checked: this.checked
        };
        if (this.button && !this.button.checkboxToggle) {
            this.cellText.textContent = this.content.value = this.content.formatted_value = this.checked
                ? this.button.checkboxTrueValue
                : this.button.checkboxFalseValue;
            response.value = this.content.value;
        }
        if (this.checked) {
            this.cellTextContainer.classList.add('checked');
        }
        else {
            this.cellTextContainer.classList.remove('checked');
        }
        console.log('toggleCheckbox', this.checked);
        // this.emit(this.CHECKED, this.checked);
        this.Events.emit(this.Events.CELL, {
            cell: this,
            evt: {
                type: 'check'
            },
            value: this.content.value,
            checked: this.checked
        });
        return response;
    };
    GridCell.prototype.getInputStyles = function () {
        var _this = this;
        var textStyles = ['font-family', 'font-size', 'font-style', 'font-weight', 'text-align'];
        var inputStyle = [];
        textStyles.forEach(function (key) {
            if (key === 'font-family') {
                inputStyle.push(key + ":" + _this.content.style[key] + ", sans-serif");
            }
            else {
                inputStyle.push(key + ":" + _this.content.style[key]);
            }
        });
        return inputStyle.join(';');
    };
    GridCell.prototype.updateSoftMerge = function (cols, direction, zIndex) {
        if (!cols || !cols.includes(this.col)) {
            return;
        }
        if (direction == 'left') {
            this.cell.style.setProperty('z-index', "" + zIndex);
        }
        else {
            this.cellBorders.style.setProperty('border-right-color', 'transparent');
        }
    };
    GridCell.prototype.updateMergeWidth = function (scrollLeft, freezeColWidth) {
        if (!this.mergeWidth)
            return;
        var width = this.mergeWidth - scrollLeft;
        if (width < this.dataset.width)
            width = this.dataset.width;
        this.cellTextContainer.style.setProperty('width', width + "px");
        if (this.content.style['text-align'] === 'center') {
            var marginLeft = width / 2 - this.dataset.width / 2;
            this.cellTextContainer.style.setProperty('margin-left', "-" + marginLeft + "px");
        }
    };
    GridCell.prototype.applyBorders = function () {
        var _this = this;
        var border = {
            top: 'none',
            bottom: 'none',
            right: 'none',
            left: 'none'
        };
        var borderOffset = {
            left: '0px',
            right: '-1px',
            top: '0px',
            bottom: '-1px'
        };
        var cellStyle = __assign({}, this.content.style);
        // merge column def style
        if (!this.row && this.Page.columnsDefs[this.col] && this.Page.columnsDefs[this.col].style) {
            cellStyle = __assign({}, cellStyle, this.Page.columnsDefs[this.col].style);
        }
        // get next row cell top border
        if (this.Page.originalContent[this.row + 1] &&
            this.Page.originalContent[this.row + 1][this.col] &&
            this.Page.originalContent[this.row + 1][this.col].style["tbs"] !== 'none') {
            cellStyle['bbs'] = this.Page.originalContent[this.row + 1][this.col].style["tbs"];
            cellStyle['bbw'] = this.Page.originalContent[this.row + 1][this.col].style["tbw"];
            cellStyle['bbc'] = this.Page.originalContent[this.row + 1][this.col].style["tbc"];
        }
        // get right cell left border
        if (this.Page.originalContent[this.row] &&
            this.Page.originalContent[this.row][this.col + 1] &&
            this.Page.originalContent[this.row][this.col + 1].style["lbs"] !== 'none') {
            cellStyle['rbs'] = this.Page.originalContent[this.row][this.col + 1].style["lbs"];
            cellStyle['rbw'] = this.Page.originalContent[this.row][this.col + 1].style["lbw"];
            cellStyle['rbc'] = this.Page.originalContent[this.row][this.col + 1].style["lbc"];
        }
        Object.keys(this.borders.names).forEach(function (name) {
            if (name === 'l') {
                if (_this.Page.originalContent[_this.row][_this.col - 1])
                    return;
            }
            if (name === 't') {
                if (_this.Page.originalContent[_this.row - 1] && _this.Page.originalContent[_this.row - 1][_this.col])
                    return;
            }
            if (cellStyle[name + "bs"] === 'none') {
                border[_this.borders.names[name]] = 'none';
                return;
            }
            var widthN = parseFloat(_this.borders.widths[cellStyle[name + "bw"]]);
            var s = widthN + "px " + cellStyle[name + "bs"] + " #" + cellStyle[name + "bc"];
            // if (opposite) {
            //   if (name == "l") border["right"] = s;
            //   if (name === "t") border["bottom"] = s;
            // } else {
            border[_this.borders.names[name]] = s;
            // }
            if (widthN > 1) {
                var offset = widthN % 2 === 0 ? -widthN / 2 : -Math.ceil(widthN / 2);
                borderOffset[_this.borders.names[name]] = offset + 'px';
            }
            else {
                borderOffset[_this.borders.names[name]] = ['t', 'l'].includes(name) ? '0px' : '-1px';
            }
        });
        var styles = [];
        Object.keys(border).forEach(function (key) {
            // this.cellBorders.style.setProperty(`border-${key}`, border[key]);
            if (border[key] != 'none')
                styles.push("border-" + key + ":" + border[key]);
        });
        if (styles.length)
            Object.keys(borderOffset).forEach(function (key) {
                // this.cellBorders.style.setProperty(key, border[key]);
                styles.push(key + ":" + border[key]);
            });
        if (styles.length) {
            this.cellBorders.style.cssText = styles.join(';');
            if (!this.cellBorders.parentNode)
                this.cell.appendChild(this.cellBorders);
        }
    };
    GridCell.prototype.applyText = function (input, textColor) {
        // if (!this.content.formatted_value && !this.content.value) {
        //   return;
        // }
        var _this = this;
        var textStyles = [
            // 'background-color',
            'color',
            'font-family',
            'font-size',
            'font-style',
            'font-weight',
            // 'height',
            // 'number-format',
            'text-align',
            'vertical-align',
            'text-wrap'
            // 'width',
            // 'vertical-align',
        ];
        var textStyle = [];
        var inputStyle = [];
        textStyles.forEach(function (key) {
            if (key === 'color') {
                if (!input) {
                    var color = textColor || "#" + _this.content.style.color;
                    textStyle.push(key + ":" + color);
                }
            }
            else if (key === 'font-family') {
                textStyle.push(key + ":" + _this.content.style[key] + ", sans-serif");
                inputStyle.push(key + ":" + _this.content.style[key] + ", sans-serif");
            }
            else if (key === 'text-align') {
                textStyle.push(key + ":" + _this.content.style[key]);
                inputStyle.push(key + ":" + _this.content.style[key]);
                if (!input)
                    if (_this.content.style[key] === 'right')
                        textStyle.push('justify-content:flex-end');
                if (!input)
                    if (_this.content.style[key] === 'center')
                        textStyle.push('justify-content:center');
            }
            else if (key === 'vertical-align') {
                if (_this.content.style[key] === 'bottom' || _this.content.style[key] === 'none')
                    if (!input)
                        textStyle.push('align-items:flex-end');
                if (_this.content.style[key] === 'center' || _this.content.style[key] === 'middle')
                    if (!input)
                        textStyle.push('align-items:center');
            }
            else if (key === 'text-wrap') {
                if (_this.content.style[key] === 'wrap' || _this.content.style[key] === 'break-word') {
                    if (!input)
                        textStyle.push('white-space:pre-wrap');
                }
                else
                    textStyle.push('white-space:nowrap');
            }
            else {
                inputStyle.push(key + ":" + _this.content.style[key]);
                textStyle.push(key + ":" + _this.content.style[key]);
            }
        });
        // textStyle.push(`width:${this.content.style.width!}`);
        if (input) {
            this.input.style.cssText = inputStyle.join(';');
            return;
        }
        this.cellTextContainer.style.cssText = textStyle.join(';');
        if (this.permission === 'no' || (!this.button && !this.content.column_name && (!("" + (this.content.formatted_value || this.content.value))))) {
            this.cellText.textContent = '';
            if (this.cellTextContainer.parentNode) {
                this.cell.removeChild(this.cellTextContainer);
            }
        }
        else {
            if (!this.cellTextContainer.parentNode)
                this.cell.appendChild(this.cellTextContainer);
            // if (this.Page.columnsDefs.length && !this.row) {
            //   this.cellText.className = 'text';
            //   let text = this.Page.columnsDefs[this.col] ? (this.Page.columnsDefs[this.col].display_name || this.Page.columnsDefs[this.col].name) : `Column ${this.col + 1}`;
            //   this.cellText.textContent = `${text}`;
            // } else if (
            if (this.content.style['number-format'] &&
                this.content.style['number-format'].indexOf('$* #,##0.00') > -1 &&
                helpers.isNumber(this.content.value)) {
                var symbol = ("" + (this.content.formatted_value || this.content.value)).trim().split(' ')[0];
                this.cellText.className = 'number';
                this.cellText.innerHTML = "<div class=\"symbol\">" + symbol + "</div>" + helpers.formatNumber(parseFloat("" + this.content.value));
            }
            else {
                this.cellText.className = 'text';
                // this.cellText.innerHTML = `${this.content.formatted_value || this.content.value}`.replace(/\n/g,'<br />');
                this.cellText.textContent = "" + (this.content.formatted_value || this.content.value);
            }
        }
        // this.cellText.style.cssText = '';
        this.cell.classList.remove('permission-no', 'permission-rw', 'permission-ro');
        this.cell.classList.add("permission-" + this.permission);
    };
    GridCell.prototype.applySoftMerge = function (hiddenColumns) {
        if (hiddenColumns === void 0) { hiddenColumns = []; }
        if (!this.created)
            return;
        // reset width
        this.cellTextContainer.style.removeProperty('width');
        this.cellTextContainer.style.removeProperty('margin-left');
        this.cell.style.setProperty('z-index', "" + (this.Page.cols - this.col));
        this.cell.classList.remove('align-right', 'align-center', 'align-left', 'merge');
        this.mergeWidth = 0;
        // check if there is any point going further
        var align = this.cellTextContainer.style.getPropertyValue('justify-content');
        if (this.button ||
            align === 'flex-end' ||
            !this.content.formatted_value ||
            this.content.style['text-wrap'] === 'wrap' ||
            !this.Page.originalContent[this.row][this.col + 1] ||
            this.Page.originalContent[this.row][this.col + 1].formatted_value) {
            return;
        }
        // measure cell width
        var cellWidth = this.Page.colWidths[this.col];
        // let clone = this.cell.cloneNode(true) as HTMLDivElement;
        var textRect = this.cellText.getBoundingClientRect();
        var textWidth = (textRect.width / this.Page.scale) - 4;
        var marginLeft = 0;
        if (this.content.style['text-align'] === 'center') {
            textWidth = textWidth / 2 + cellWidth / 2;
        }
        // const textWidth = (textRect.width * size - 2) / this.Page.scale;
        if (textWidth < cellWidth) {
            return;
        }
        var colWidth = cellWidth;
        // find where to merge to
        var colCells = [this.col];
        for (var colMerge = this.col + 1; colMerge < this.Page.originalContent[this.row].length; colMerge++) {
            if (!this.Page.originalContent[this.row][colMerge] ||
                this.Page.originalContent[this.row][colMerge].formatted_value !== '' ||
                colWidth > textWidth ||
                hiddenColumns.indexOf(colMerge) > -1) {
                break;
            }
            colWidth += Math.round(parseFloat(this.Page.originalContent[this.row][colMerge].style.width));
            colCells.push(colMerge);
        }
        var colLeftWidth = cellWidth;
        var colCellsLeft = [];
        if (this.content.style['text-align'] === 'center') {
            for (var colMerge = this.col - 1; colMerge >= 0; colMerge--) {
                if (!this.Page.originalContent[this.row][colMerge] ||
                    this.Page.originalContent[this.row][colMerge].formatted_value !== '' ||
                    colLeftWidth > textWidth ||
                    hiddenColumns.indexOf(colMerge) > -1) {
                    break;
                }
                colLeftWidth += Math.round(parseFloat(this.Page.originalContent[this.row][colMerge].style.width));
                colCellsLeft.push(colMerge);
            }
        }
        colCells.pop();
        this.cellBorders.style.setProperty('border-right-color', 'transparent');
        this.cellTextContainer.style.setProperty('width', colWidth + "px");
        if (this.content.style['text-align'] === 'center') {
            marginLeft = colWidth / 2 - cellWidth / 2;
            this.cellTextContainer.style.setProperty('margin-left', "-" + marginLeft + "px");
        }
        else if (this.content.style['text-align'] === 'left') {
            this.mergeWidth = colWidth;
        }
        this.cell.classList.add("align-" + this.content.style['text-align']);
        this.dataset.overflow = colWidth;
        this.updateMergeWidth(this.Page.scrollLeft);
        this.Events.emit(this.Events.CELL, {
            cell: this,
            data: {
                left: colCellsLeft,
                right: colCells,
                zIndex: this.Page.cols - this.col
            },
            evt: {
                type: 'merge'
            }
        });
    };
    GridCell.prototype.applyButton = function () {
        var _this = this;
        if (this.button && this.permission != 'no' && (!this.Page.columnsDefs.length || (this.Page.columnsDefs && this.row))) {
            this.isButton = true;
            this.canEditButton = true;
            this.cellTextContainer.classList.add('grid-button');
            if (this.button.type === 'select') {
                if (!this.cellPopper) {
                    this.cellPopper = document.createElement('div');
                    this.cellPopper.className = 'grid-popper';
                    this.cellPopper.style.setProperty('min-width', this.dataset.width + "px");
                    this.cellPopper.addEventListener('mouseleave', function (evt) {
                        // this.emit(this.STOP);
                        _this.Events.emit(_this.Events.CELL, {
                            cell: _this,
                            evt: {
                                type: 'blur'
                            }
                        });
                    });
                }
                this.hasButtonOptions = true;
                this.canEditButton = false;
                this.cellPopper.innerHTML = '';
                this.button.options.forEach(function (option) {
                    var a = document.createElement('a');
                    a.textContent = option;
                    a.addEventListener('click', function () {
                        var done = false;
                        if (option !== _this.content.formatted_value) {
                            _this.cellText.textContent = _this.content.value = _this.content.formatted_value = option;
                            done = true;
                        }
                        // this.emit(this.editValue, option);
                        // this.emit(this.DONE, option);
                        // this.emit(this.STOP);
                        _this.Events.emit(_this.Events.CELL, {
                            cell: _this,
                            evt: {
                                type: 'blur'
                            },
                            done: done
                        });
                    });
                    _this.cellPopper.appendChild(a);
                });
                // this.cell.appendChild(this.cellPopper);
            }
            else if (this.button.type === 'rotate') {
                this.hasButtonOptions = true;
                this.canEditButton = false;
            }
            else if (this.button.type === 'checkbox') {
                if (!this.cellCheckbox) {
                    this.cellCheckbox = document.createElement('div');
                    this.cellCheckbox.className = 'checkbox';
                }
                // this.hasButtonOptions = true;
                this.canEditButton = true;
                this.cellTextContainer.classList.remove('grid-button');
                this.cellTextContainer.classList.add('grid-checkbox');
                // this.cellText.classList.add('checkbox');
                if (!this.cellTextContainer.contains(this.cellCheckbox)) {
                    this.cellTextContainer.prepend(this.cellCheckbox);
                }
                if (!this.button.checkboxToggle) {
                    if (this.content.value == this.button.checkboxTrueValue) {
                        this.checked = true;
                        this.cellTextContainer.classList.add('checked');
                    }
                    else {
                        this.checked = false;
                        this.cellTextContainer.classList.remove('checked');
                    }
                }
                // this.cellCheckbox.onclick = () => {
                // console.log('checkbox');
                // this.toggleCheckbox();
                // };
            }
        }
        else {
            this.isButton = false;
            this.hasButtonOptions = false;
            this.cellTextContainer.classList.remove('grid-button');
            this.cellTextContainer.classList.remove('grid-checkbox');
            if (this.cellCheckbox && this.cellTextContainer.contains(this.cellCheckbox)) {
                this.cellTextContainer.removeChild(this.cellCheckbox);
            }
            // this.cellText.classList.remove('checkbox');
            // if (this.cell.contains(this.cellPopper)) this.cell.removeChild(this.cellPopper);
        }
        if (this.content.link) {
            this.cellTextContainer.classList.add('link');
        }
        else {
            this.cellTextContainer.classList.remove('link');
        }
    };
    GridCell.prototype.destroyPopper = function () {
        if (!this.buttonPopper)
            return;
        this.buttonPopper.destroy();
        this.buttonPopper = undefined;
        this.cellPopper.style.setProperty('display', 'none');
        window.removeEventListener('click', this.onWindowClick);
    };
    GridCell.prototype.updateSelectOptions = function () {
        for (var i = 0; i < this.cellPopper.childNodes.length; i++) {
            var a_1 = this.cellPopper.childNodes[i];
            a_1.classList.remove('selected');
        }
        var a = this.cellPopper.childNodes[this.selectedOption];
        a.classList.add('selected');
    };
    GridCell.prototype.setSelectOption = function (key) {
        if (!this.button)
            return;
        var option = this.button.options[this.selectedOption];
        var done = false;
        if (option !== this.content.formatted_value) {
            this.cellText.textContent = this.content.value = this.content.formatted_value = option;
            done = true;
        }
        this.Events.emit(this.Events.CELL, {
            cell: this,
            evt: {
                type: 'blur'
            },
            done: done
        });
    };
    return GridCell;
}(Emitter_1.default));
exports.GridCell = GridCell;
//# sourceMappingURL=GridCell.js.map