"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 __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
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 GridContent_1 = __importDefault(require("./GridContent"));
var helpers = new Helpers_1.default();
var GridCell = /** @class */ (function (_super) {
    __extends(GridCell, _super);
    function GridCell(params) {
        var _this = _super.call(this) || this;
        _this.params = params;
        _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.inputStyles = ['color', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-align'];
        _this.textStyles = [
            // 'background-color',
            'color',
            'font-family',
            'font-size',
            'font-style',
            'font-weight',
            // 'height',
            // 'number-format',
            'text-align',
            'justify-content',
            'align-items',
            'text-wrap'
            // 'width',
            // 'vertical-align',
        ];
        _this.cellStyles = [
            'background-color',
            'color',
            'font-family',
            'font-size',
            'font-style',
            'font-weight',
            'height',
            'text-align',
            'text-wrap',
            'width',
            'vertical-align'
        ];
        _this.init = false;
        _this.type = 'cell';
        _this.freeze = '';
        _this.permission = 'rw';
        _this.reference = '';
        _this.position = {
            row: -1,
            col: -1
        };
        _this.index = {
            row: -1,
            col: -1
        };
        _this.hasHistory = false;
        _this.isButton = false;
        _this.hasButtonOptions = false;
        _this.canEditButton = false;
        _this.button = null;
        _this.link = null;
        _this.style = null;
        _this.isImage = false;
        _this.hidden = false;
        _this.row = -1;
        _this.col = -1;
        _this.checked = false;
        _this.highlightTimer = null;
        // private initialized: boolean = false;
        _this.oldValue = '';
        _this.borderStyles = {};
        _this.mergedCells = {
            cells: [],
            last: []
        };
        _this.selectedOption = 0;
        _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.button = params.button;
        _this.type = 'cell';
        // this.hidden = params.hidden;
        // this.link = params.col.link || null;
        // cell data
        var dataset = _this.getDataset(params);
        _this.dataset = dataset;
        // backwards compatibility
        _this.position.row = dataset.row;
        _this.position.col = dataset.col;
        _this.index.row = dataset.row;
        _this.index.col = dataset.col;
        _this.row = params.content.index.row;
        _this.col = params.content.index.col;
        _this.cell = document.createElement('div');
        _this.cellBordersOffset = document.createElement('div');
        _this.cellTextContainer = document.createElement('div');
        // soft merges
        // this.updateSoftMerge();
        // cell reference
        _this.reference = "" + helpers.toColumnName(params.colIndex + 1) + (params.rowIndex + 1);
        return _this;
    }
    Object.defineProperty(GridCell.prototype, "VALUE", {
        get: function () {
            return 'value';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GridCell.prototype, "DONE", {
        get: function () {
            return 'done';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GridCell.prototype, "CANCEL", {
        get: function () {
            return 'cancel';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GridCell.prototype, "STOP", {
        get: function () {
            return 'stop';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GridCell.prototype, "CHECKED", {
        get: function () {
            return 'checked';
        },
        enumerable: true,
        configurable: true
    });
    GridCell.prototype.create = function () {
        this.init = true;
        this.cell.className = 'grid-cell';
        if (this.freeze === 'common') {
            this.cell.style.setProperty('transform', "translate(" + this.dataset.x + "px, " + this.dataset.y + "px)");
        }
        else {
            this.cell.style.setProperty('transform', "translateX(" + this.dataset.x + "px)");
        }
        this.cell.style.setProperty('z-index', "" + this.params.zIndexCol);
        this.cell.style.setProperty('width', this.dataset.width + "px");
        this.cell.style.setProperty('height', this.dataset.height + "px");
        this.cell.dataset.row = this.params.rowIndex.toString();
        this.cell.dataset.col = this.params.colIndex.toString();
        this.cell.dataset.r = this.params.rowIndex.toString();
        this.cell.dataset.c = this.params.colIndex.toString();
        // cell.dataset.width = dataset.width.toString();
        // cell.dataset.height = dataset.height.toString();
        // cell.dataset.overflow = dataset.width.toString();
        // cell.dataset.x = this.params.x.toString();
        // cell.dataset.y = this.params.y.toString();
        // this.cell = cell;
        // background
        // this.cellImage = document.createElement('img');
        this.cellBackground = document.createElement('div');
        this.cellBackground.className = 'grid-background';
        this.cellBackground.style.setProperty('background-color', "#" + this.params.content.style['background-color']);
        // this.cellBackground.style.setProperty('width', `${this.dataset.width + 1}px`);
        // this.cellBackground.style.setProperty('height', `${this.dataset.height + 1}px`);
        // cell.appendChild(this.cellBackground);
        // borders
        this.cellBorders = document.createElement('div');
        this.cellBorders.className = 'grid-border';
        // this.cellBorders.style.setProperty('width', `${this.dataset.width}px`);
        // this.cellBordersOffset = document.createElement('div');
        this.cellBordersOffset.className = 'grid-border-offset';
        this.cellBorders.appendChild(this.cellBordersOffset);
        // this.cell.appendChild(this.cellBorders);
        // history
        // this.cell.appendChild(this.cellHistory);
        // text
        // this.cellTextContainer = document.createElement('div');
        this.cellTextContainer.className = 'grid-text';
        this.cellText = document.createElement('div');
        this.cellTextContainer.appendChild(this.cellText);
        // cell.appendChild(this.cellTextContainer);
        // button menu
        // update
        this.appendChildren();
        this.update(this.params.content);
        this.updateSoftMerge();
    };
    GridCell.prototype.update = function (content) {
        this.params.content = __assign(__assign({}, this.params.content), content);
        this.params.row[this.col] = this.params.content;
        this.refresh();
    };
    GridCell.prototype.refresh = function () {
        if (!this.init)
            return;
        var backgroundColor = this.style && this.style.background ? this.style.background : "#" + this.params.content.style['background-color'];
        var textColor = this.style && this.style.color ? this.style.color : "#" + this.params.content.style['color'];
        this.cellBackground.style.setProperty('background-color', backgroundColor);
        this.cell.classList.remove('light', 'dark');
        this.cell.classList.add(helpers.getContrastYIQ(backgroundColor));
        if (this.cellBackgroundHighlight) {
            this.cellBackgroundHighlight.style.setProperty('background-color', textColor);
        }
        if (("" + this.params.content.value).indexOf('data:image') > -1) {
            this.cell.classList.add("image");
            if (!this.cellImage) {
                this.cellImage = document.createElement('img');
            }
            this.cellImage.src = "" + this.params.content.value;
            this.cell.innerHTML = '';
            this.cell.appendChild(this.cellImage);
            this.isImage = true;
        }
        else {
            // this.cellBackground.style.removeProperty('background-image');
            this.cell.classList.remove("image");
            if (this.cell.contains(this.cellImage)) {
                this.cell.removeChild(this.cellImage);
                this.appendChildren();
            }
            this.isImage = false;
            this.applyButton();
            this.applyBorders();
            this.applyText(textColor);
        }
        // this.updateSoftMerge();
    };
    GridCell.prototype.renderer = function () { };
    GridCell.prototype.setButton = function (button) {
        this.button = button;
        this.refresh();
    };
    GridCell.prototype.setFound = function (n) {
        if (!n) {
            this.cell.classList.remove('cell-found');
        }
        else {
            this.cell.classList.add("cell-found");
        }
    };
    GridCell.prototype.setStyle = function (style) {
        this.style = style;
        this.refresh();
    };
    GridCell.prototype.setPermission = function (permission) {
        this.permission = permission;
        this.cell.classList.add("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.setRowIndex = function (row, y) {
        this.dataset.row = row;
        this.index.row = row;
        this.dataset.y = y;
        this.cell.dataset.row = row.toString();
        // if (this.freeze === 'common') {
        //   this.cell.style.setProperty('transform', `translate(${this.dataset.x}px, ${this.dataset.y}px)`);
        // } else {
        //   this.cell.style.setProperty('transform', `translateX(${this.dataset.x}px)`);
        // }
    };
    GridCell.prototype.edit = function (value, touch) {
        var _this = this;
        // let p: Promise<any> = new Promise((resolve, reject) => {
        if (this.permission !== 'rw') {
            // reject(this.permission);
            this.emit(this.STOP);
            return;
        }
        if (this.button && ['select', 'rotate'].indexOf(this.button.type) > -1) {
            return;
        }
        if (this.input && this.input.parentElement) {
            this.input.parentElement.removeChild(this.input);
        }
        var input = document.createElement('input');
        this.input = input;
        input.classList.add('grid-input');
        input.value = value || "" + this.params.content.formatted_value || "" + this.params.content.value;
        this.oldValue = "" + this.params.content.formatted_value || "" + this.params.content.value;
        this.cellText.innerHTML = this.params.content.formatted_value = this.params.content.value = input.value;
        input.style.setProperty('width', this.dataset.width + "px");
        this.inputStyles.forEach(function (style) {
            if (style === 'color')
                return;
            input.style.setProperty(style, _this.params.content.style[style]);
        });
        this.cell.style.setProperty('z-index', '10000');
        var done = false;
        this.cell.appendChild(this.cellTextContainer);
        var interval = setInterval(function () {
            if (input.parentElement === null)
                return;
            clearInterval(interval);
            input.addEventListener('keydown', function (evt) {
                if ((['ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown'].indexOf(evt.key) > -1 && value) ||
                    ['Enter', 'Tab'].indexOf(evt.key) > -1) {
                    done = true;
                    _this.emit(_this.DONE, input.value);
                    _this.emit(_this.STOP, evt.key);
                }
            });
            input.addEventListener('keyup', function () {
                _this.cellText.textContent = _this.params.content.formatted_value = _this.params.content.value = input.value;
                _this.emit(_this.VALUE, input.value);
            });
            input.addEventListener('blur', function (evt) {
                console.log(evt);
                return;
                _this.input.parentElement.removeChild(_this.input);
                _this.cell.style.setProperty('z-index', "" + _this.params.zIndexCol);
                if (done)
                    return;
                if (_this.cellText.textContent === _this.oldValue) {
                    _this.emit(_this.CANCEL);
                }
                else {
                    _this.emit(_this.DONE, input.value);
                }
                _this.emit(_this.STOP);
            });
            // if (!touch) {
            input.focus();
            // }
            if (!value) {
                input.selectionStart = 0;
                input.selectionEnd = 999;
            }
        }, 20);
        if (!touch) {
            this.cell.appendChild(input);
        }
        // });
        // return p;
    };
    GridCell.prototype.onButton = function () {
        if (!this.button || this.buttonPopper)
            return false;
        // if (this.button.type === 'select') {
        //   this.buttonPopper = new Popper(this.cell, this.cellPopper, { placement: 'bottom-start' });
        //   this.cellPopper.style.setProperty('display', 'block');
        //   setTimeout(() => {
        //     window.addEventListener('click', this.onWindowClick);
        //   }, 300);
        //   return true;
        // }
        this.oldValue = "" + this.params.content.formatted_value || "" + this.params.content.value;
        if (this.button.type === 'checkbox') {
            // return true;
        }
        if (this.button.type === 'rotate') {
            var value = helpers.getNextValueInArray(this.params.content.formatted_value || this.params.content.value, this.button.options);
            this.cellText.textContent = this.params.content.formatted_value = value;
            this.emit(this.VALUE, value);
            this.emit(this.DONE, value);
            this.emit(this.STOP);
            return true;
        }
        return false;
    };
    GridCell.prototype.cancel = function (restore) {
        this.destroyPopper();
        if (restore) {
            this.cellText.textContent = this.oldValue;
            this.params.content.value = this.oldValue;
            this.params.content.formatted_value = this.oldValue;
        }
        if (this.input) {
            this.input.blur();
        }
    };
    GridCell.prototype.selected = function (n, sides) {
        var _a;
        if (sides === void 0) { sides = []; }
        this.cell.classList.remove('selected', 'top', 'left', 'bottom', 'right', 'first');
        if (n) {
            (_a = this.cell.classList).add.apply(_a, __spreadArrays(['selected'], sides));
        }
    };
    GridCell.prototype.setFreeze = function (which, cell, cell2) {
        var _this = this;
        this.cell.style.setProperty('transform', "translateX(" + this.dataset.x + "px)");
        if (!which && !this.freeze)
            return;
        this.freeze = which;
        this.hidden = false;
        // reset borders
        this.applyBorders();
        // this.cell.style.setProperty('width', `${parseFloat(this.params.col.style.width) + 1}px`);
        // this.cell.style.setProperty('height', `${parseFloat(this.params.col.style.height) + 1}px`);
        // take border properties from the next cell
        if (!cell)
            return;
        var borderStyles = this.transformStyle(cell.params.content.style, 'cell');
        var borderStyles2 = {};
        if (cell2) {
            borderStyles2 = this.transformStyle(cell2.params.content.style, 'cell');
        }
        Object.keys(borderStyles).forEach(function (key) {
            if (which === 'common' || which === 'col') {
                if (key.indexOf('border-left') > -1)
                    _this.cellBordersOffset.style.setProperty(key.replace('left', 'right'), borderStyles[key].replace('left', 'right'));
            }
            if (which === 'common' || which === 'row') {
                if (key.indexOf('border-top') > -1)
                    _this.cellBordersOffset.style.setProperty(key.replace('top', 'bottom'), borderStyles[key].replace('top', 'bottom'));
            }
        });
        Object.keys(borderStyles2).forEach(function (key) {
            if (key.indexOf('border-top') > -1)
                _this.cellBordersOffset.style.setProperty(key.replace('top', 'bottom'), borderStyles2[key].replace('top', 'bottom'));
        });
        // this.updateSoftMerge();
        if (which === 'common') {
            this.cell.style.setProperty('transform', "translate(" + this.dataset.x + "px, " + this.dataset.y + "px)");
        }
    };
    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.params.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;
        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, __spreadArrays(['history'], users));
            if (this.cellHistory && this.cellHistory.parentNode) {
                this.cell.removeChild(this.cellHistory);
                this.cellHistory = null;
            }
        }
    };
    GridCell.prototype.updateSoftMerge = function (hiddenColumns) {
        var _this = this;
        if (hiddenColumns === void 0) { hiddenColumns = []; }
        if (!this.init)
            return;
        this.cellBordersOffset.style.removeProperty('border-left-color');
        this.cellBordersOffset.style.removeProperty('border-right-color');
        this.applyBorders();
        this.cellTextContainer.style.setProperty('width', this.dataset.width + "px");
        this.cellText.style.removeProperty('margin-left');
        this.cellText.style.removeProperty('margin-right');
        this.dataset.overflow = this.dataset.width;
        // ensure merging cell is visible
        if (this.params.mergedCells.last.indexOf(this.params.colIndex) > -1) {
            this.cellBordersOffset.style.setProperty('border-left-color', 'transparent');
            // this.cellBackground.style.setProperty('background-color', 'transparent');
        }
        else if (this.params.mergedCells.cells.indexOf(this.params.colIndex) > -1) {
            this.cellBordersOffset.style.setProperty('border-left-color', 'transparent');
            this.cellBordersOffset.style.setProperty('border-right-color', 'transparent');
            // this.cellBackground.style.setProperty('background-color', 'transparent');
        }
        else {
            // this.cellBackground.style.setProperty('background-color', `#${this.params.col.style['background-color']}`);
        }
        // clear any current merge references
        this.mergedCells.cells.forEach(function (col) {
            if (_this.params.mergedCells.cells.indexOf(col) > -1) {
                _this.params.mergedCells.cells.splice(_this.params.mergedCells.cells.indexOf(col), 1);
            }
        });
        this.mergedCells.last.forEach(function (col) {
            if (_this.params.mergedCells.last.indexOf(col) > -1) {
                _this.params.mergedCells.last.splice(_this.params.mergedCells.last.indexOf(col), 1);
            }
        });
        this.mergedCells = {
            cells: [],
            last: []
        };
        // check if there is any point going further
        var align = this.cellTextContainer.style.getPropertyValue('justify-content');
        if (align === 'flex-end' ||
            this.cellText.textContent === '' ||
            this.params.content.style['text-wrap'] === 'wrap' ||
            (this.params.row[this.params.colIndex + 1] && this.params.row[this.params.colIndex + 1].formatted_value)) {
            if (align === 'flex-end') {
                var offset = this.dataset.overflow - this.dataset.width;
                this.cellText.style.setProperty('margin-right', offset + "px");
            }
            return;
        }
        // measure cell width
        var clone = this.cell.cloneNode(true);
        var colWidth = this.dataset.width;
        this.params.mergeEl.innerHTML = '';
        this.params.mergeEl.appendChild(clone);
        var textContainer = clone.getElementsByClassName('grid-text')[0];
        if (!textContainer)
            return;
        textContainer.classList.remove('grid-button');
        var text = textContainer.getElementsByTagName('div')[0];
        text.style.setProperty('padding', '0');
        var textRect = text.getBoundingClientRect();
        if (textRect.width < this.dataset.width) {
            return;
        }
        // find where to merge to
        var colLast = this.params.colIndex;
        var colCells = [];
        for (var colMerge = this.params.colIndex + 1; colMerge < this.params.row.length; colMerge++) {
            if (!this.params.row[colMerge] ||
                this.params.row[colMerge].formatted_value !== '' ||
                colWidth > textRect.width ||
                hiddenColumns.indexOf(colMerge) > -1) {
                break;
            }
            colLast++;
            colWidth += Math.round(parseFloat(this.params.row[colMerge].style.width));
            if (this.params.mergedCells.cells.indexOf(colMerge) < 0) {
                this.params.mergedCells.cells.push(colMerge);
            }
            colCells.push(colMerge);
        }
        if (this.params.mergedCells.last.indexOf(colLast) < 0)
            this.params.mergedCells.last.push(colLast);
        this.mergedCells.last = [colLast];
        this.mergedCells.cells = colCells;
        // adjust params
        this.cellBordersOffset.style.setProperty('border-right-color', 'transparent');
        this.cellTextContainer.style.setProperty('width', colWidth + 1 + "px");
        // this.cellBackground.style.setProperty('width', `${colWidth}px`);
        this.dataset.overflow = colWidth;
        this.cell.dataset.overflow = colWidth.toString();
        // let align = this.cellTextContainer.style.getPropertyValue('justify-content');
        // if (align === 'center') {
        //   console.log('DATASET', this.dataset);
        //   let offset = (this.dataset.overflow - this.dataset.width) / 2;
        //   console.log('Offset', offset);
        //   this.cellText.style.setProperty('margin-left', `${offset}px`);
        // }
    };
    GridCell.prototype.setSize = function (which, size) {
        this.dataset[which] = size;
        this.cell.style.setProperty(which, this.dataset[which] + "px");
        // this.cellBackground.style.setProperty(which, `${this.dataset[which] + 1}px`);
        if (which === 'width') {
            // this.cellBorders.style.setProperty('width', `${this.dataset.width}px`);
            this.cellTextContainer.style.setProperty(which, this.dataset.width + "px");
        }
    };
    GridCell.prototype.setOffset = function (offset, which) {
        if (this.freeze === 'common') {
            var translate = which === 'width'
                ? "translate(" + (this.dataset.x + offset) + "px, " + this.dataset.y + "px)"
                : "translate(" + this.dataset.x + "px, " + (this.dataset.y + offset) + "px)";
            // console.log(translate, which);
            this.cell.style.setProperty('transform', translate);
        }
        else {
            this.cell.style.setProperty('transform', "translateX(" + (this.dataset.x + offset) + "px)");
        }
    };
    GridCell.prototype.setXPosition = function (position, move) {
        this.dataset.x += position;
        if (!move)
            return;
        this.cell.style.setProperty('transform', "translateX(" + this.dataset.x + "px)");
    };
    GridCell.prototype.setYPosition = function (position, move) {
        this.dataset.y += position;
        if (this.freeze === 'common') {
            this.cell.style.setProperty('transform', "translate(" + this.dataset.x + "px, " + this.dataset.y + "px)");
        }
    };
    GridCell.prototype.getDetails = function () {
        return {
            content: this.params.content,
            row: this.row,
            col: this.col,
            position: this.position,
            index: this.index,
            dataset: this.dataset,
            reference: this.reference,
            link: this.params.content.link,
            button: this.button,
            history: this.hasHistory,
            checked: this.checked
        };
    };
    GridCell.prototype.getFlattenStyles = function (only) {
        var htmlStyle = {};
        var styles = this.params.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.getValue = function () {
        return this.params.content.formatted_value;
    };
    GridCell.prototype.getRawValue = function () {
        return this.params.content.value;
    };
    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.params.content.checked = this.checked;
        var response = {
            checked: this.checked
        };
        if (this.button && this.button.checkboxTrueValue) {
            this.cellText.textContent = this.params.content.value = this.params.content.formatted_value = this.checked
                ? this.button.checkboxTrueValue
                : this.button.checkboxFalseValue;
            response.value = this.params.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);
        return response;
    };
    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.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];
        if (option === this.params.content.formatted_value) {
            this.emit(this.STOP, key);
            return;
        }
        this.cellText.textContent = this.params.content.value = this.params.content.formatted_value = option;
        this.emit(this.VALUE, option);
        this.emit(this.DONE, option);
        this.emit(this.STOP, key);
    };
    GridCell.prototype.appendChildren = function () {
        this.cell.appendChild(this.cellBackground);
        this.cell.appendChild(this.cellBorders);
        // this.cell.appendChild(this.cellHistory);
        this.cell.appendChild(this.cellTextContainer);
    };
    GridCell.prototype.getDataset = function (params) {
        return {
            width: Math.round(parseFloat(params.content.style.width)),
            height: Math.round(parseFloat(params.content.style.height)),
            overflow: Math.round(parseFloat(params.content.style.width)),
            x: params.x,
            y: params.y,
            row: params.rowIndex,
            col: params.colIndex
        };
    };
    GridCell.prototype.applyBorders = function () {
        var _this = this;
        if (!this.init)
            return;
        // this.cellBordersOffset.style.setProperty('border-color', `#${this.params.col.style['background-color']}`);
        this.borderStyles = this.transformStyle(this.params.content.style, 'cell');
        // if (!Object.keys(this.borderStyles).length) {
        //   if (this.cellBorders.parentNode) {
        //     this.cell.removeChild(this.cellBorders);
        //   }
        //   return;
        // }
        // if (!this.cellBorders.parentNode) {
        //   this.cell.appendChild(this.cellBorders);
        // }
        Object.keys(this.borderStyles).forEach(function (key) {
            _this.cellBordersOffset.style.setProperty(key, _this.borderStyles[key]);
        });
        // grab opposite border styles
        if (this.params.row[this.dataset.col + 1]) {
            var borderStyles2_1 = this.transformStyle(this.params.row[this.dataset.col + 1].style, 'cell', true);
            Object.keys(borderStyles2_1).forEach(function (key) {
                if (key.indexOf('border-left') > -1)
                    _this.cellBordersOffset.style.setProperty(key.replace('left', 'right'), borderStyles2_1[key].replace('left', 'right'));
            });
        }
        if (GridContent_1.default.content[this.row + 1] && GridContent_1.default.content[this.row + 1][this.col]) {
            var borderStyles2_2 = this.transformStyle(GridContent_1.default.content[this.row + 1][this.col].style, 'cell', true);
            Object.keys(borderStyles2_2).forEach(function (key) {
                if (key.indexOf('border-top') > -1)
                    _this.cellBordersOffset.style.setProperty(key.replace('top', 'bottom'), borderStyles2_2[key].replace('top', 'bottom'));
            });
        }
    };
    GridCell.prototype.applyText = function (textColor) {
        var _this = this;
        var textStyles = this.transformStyle(this.params.content.style, 'text');
        this.cellTextContainer.removeAttribute('style');
        Object.keys(textStyles).forEach(function (key) {
            _this.cellTextContainer.style.setProperty(key, textStyles[key]);
        });
        this.cellTextContainer.style.setProperty('color', textColor);
        if (!this.button && (this.permission === 'no' || !("" + (this.params.content.formatted_value || this.params.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.params.content.style['number-format'] &&
                this.params.content.style['number-format'].indexOf('$* #,##0.00') > -1 &&
                helpers.isNumber(this.params.content.value)) {
                var symbol = ("" + (this.params.content.formatted_value || this.params.content.value)).trim().split(' ')[0];
                this.cellText.className = 'number';
                this.cellText.innerHTML = "<div class=\"symbol\">" + symbol + "</div>" + helpers.formatNumber(parseFloat("" + this.params.content.value));
            }
            else {
                this.cellText.className = 'text';
                // this.cellText.innerHTML = `${this.params.content.formatted_value || this.params.content.value}`.replace(/\n/g,'<br />');
                this.cellText.textContent = "" + (this.params.content.formatted_value || this.params.content.value);
            }
        }
        this.cellTextContainer.style.setProperty('width', this.cell.style.width);
        this.cell.classList.remove('permission-no', 'permission-rw', 'permission-ro');
        this.cell.classList.add("permission-" + this.permission);
        // this.cellStatus.style.setProperty('width', this.cell.style.width);
    };
    GridCell.prototype.applyButton = function () {
        var _this = this;
        if (this.button) {
            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.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 () {
                        if (option === _this.params.content.formatted_value) {
                            _this.emit(_this.STOP);
                            return;
                        }
                        _this.cellText.textContent = _this.params.content.formatted_value = option;
                        _this.emit(_this.VALUE, option);
                        _this.emit(_this.DONE, option);
                        _this.emit(_this.STOP);
                    });
                    _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.checkboxTrueValue) {
                    if (this.params.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.params.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.transformStyle = function (contentStyle, which, opposite) {
        var newStyle = {};
        if (which === 'cell') {
            // newStyle['background-color'] = '#' + contentStyle['background-color'];
            for (var key in this.borders.names) {
                // prevent border double up
                if (!opposite && key === 'l') {
                    if (GridContent_1.default.content[this.row][this.col - 1])
                        continue;
                }
                if (!opposite && key === 't') {
                    if (GridContent_1.default.content[this.row - 1] && GridContent_1.default.content[this.row - 1][this.col])
                        continue;
                }
                var name_2 = this.borders.names[key];
                var width = this.borders.widths[contentStyle[key + "bw"]] + 'px';
                var style = this.borders.styles[contentStyle[key + "bs"]];
                var color = '#' + contentStyle[key + "bc"].replace('#', '');
                if (style === 'none') {
                    if (['left'].indexOf(name_2) > -1 && !this.dataset.col) {
                        // newStyle[name] = '0px';
                    }
                    continue;
                }
                var widthN = parseFloat(width);
                var widthOffset = 0;
                if (['left'].indexOf(name_2) > -1) {
                    // widthOffset = this.dataset.col ? 1 : 0;
                    // if(this.dataset.col) widthN++;
                }
                if (['bottom'].indexOf(name_2) > -1) {
                    widthOffset = -1;
                }
                // if ((name === 'top' && !this.params.rowIndex) || (name === 'left' && !this.params.colIndex)) {
                //   newStyle[name] = '0px';
                //   widthN--;
                // }
                if (widthN > 1) {
                    var offset = widthN % 2 === 0 ? -widthN / 2 : -Math.ceil(widthN / 2);
                    newStyle[name_2] = offset + 'px';
                }
                else if (widthN <= 1 && ['left'].indexOf(name_2) > -1) {
                    // newStyle[name] = '0px';
                }
                newStyle["border-" + name_2] = width + " " + style + " " + color;
            }
        }
        if (which === 'text') {
            // newStyle['background-color'] = '#' + contentStyle['background-color'];
            this.textStyles.forEach(function (name) {
                if (name === 'justify-content') {
                    if (contentStyle['text-align'] === 'right') {
                        newStyle['justify-content'] = 'flex-end';
                    }
                    if (contentStyle['text-align'] === 'center') {
                        newStyle['justify-content'] = 'center';
                    }
                }
                else if (name === 'align-items') {
                    // vertical-align
                    if (contentStyle['vertical-align'] === 'bottom' || contentStyle['vertical-align'] === 'none') {
                        newStyle['align-items'] = 'flex-end';
                    }
                    else if (contentStyle['vertical-align'] === 'middle' || contentStyle['vertical-align'] === 'center') {
                        newStyle['align-items'] = 'center';
                    }
                }
                else if (name === 'text-wrap') {
                    if (contentStyle['text-wrap'] === 'wrap' || contentStyle['word-wrap'] === 'break-word') {
                        newStyle['white-space'] = 'pre-wrap';
                        newStyle['line-height'] = '1.1';
                    }
                    else {
                        newStyle['white-space'] = 'nowrap';
                    }
                }
                else if (name === 'color') {
                    newStyle.color = '#' + contentStyle.color;
                }
                else if (name === 'font-family') {
                    newStyle["" + name] = contentStyle["" + name] + ', sans-serif';
                }
                else {
                    newStyle["" + name] = contentStyle["" + name];
                }
            });
        }
        return newStyle;
    };
    return GridCell;
}(Emitter_1.default));
exports.GridCell = GridCell;
//# sourceMappingURL=GridCell.js.map