'use strict';

const core = require('./core-859ae5a6.js');
const utils = require('./utils-2a7c8f6e.js');

const COLUMN_CONTEXT_MENU = [
    {
        label: 'Pin Left',
        value: 'left'
    },
    {
        label: 'Pin Right',
        value: 'right'
    },
    {
        label: 'Unpin',
        value: null
    }
];
var Translations;
(function (Translations) {
    Translations["SELECT"] = "Select";
    Translations["DESELECT"] = "Deselect";
})(Translations || (Translations = {}));
const FILTER_TYPES = ['contains', 'ends-with', 'equals', 'starts-with'];
var ColumnClasses;
(function (ColumnClasses) {
    ColumnClasses["cell"] = "anj-cell";
    ColumnClasses["header"] = "anj-header-cell";
    ColumnClasses["number"] = "anj-datatype-number";
    ColumnClasses["overflowCell"] = "anj-overflow-cell";
    ColumnClasses["overflowHeader"] = "anj-overflow-header";
    ColumnClasses["pinBorder"] = "anj-pin-border";
    ColumnClasses["selectable"] = "anj-selectable";
    ColumnClasses["selected"] = "anj-selected-col";
    ColumnClasses["sorted"] = "anj-sorted";
})(ColumnClasses || (ColumnClasses = {}));
let colId = 0;
class ColumnRenderer {
    constructor(column) {
        this.column = column;
    }
    static classFromColumnName(name) {
        return `anj-col-${name.replace(/\//g, '-')}`;
    }
    static classFromPinned(pinned) {
        if (!pinned) {
            return;
        }
        return `anj-pinned-${pinned}`;
    }
    static pinnedBorderClass(index, boundaries) {
        return index === boundaries.lastLeftPinned || index === boundaries.firstRightPinned ? ColumnClasses.pinBorder : undefined;
    }
    static columnHeaderClasses(column) {
        return utils.concatClasses(ColumnClasses.header, column.sortIndex > -1 ? ColumnClasses.sorted : undefined, column.overflow === 'all' || column.overflow === 'header' ? ColumnClasses.overflowHeader : undefined, ColumnRenderer.columnClasses(column));
    }
    static columnCellClasses(column) {
        return utils.concatClasses(ColumnClasses.cell, column.overflow === 'all' || column.overflow === 'cell' ? ColumnClasses.overflowCell : undefined, ColumnRenderer.columnClasses(column));
    }
    static columnAttributes(column, cIndex, row) {
        return {
            colspan: column.span,
            'data-column-index': cIndex,
            'data-column-field': column.field,
            'data-row-key': row[column.table.rowKey]
        };
    }
    static columnClasses(column) {
        return [
            ColumnRenderer.classFromColumnName(column.name),
            ColumnRenderer.classFromPinned(column.pinned),
            column.table.selectedColumnFields.includes(column.field) ? ColumnClasses.selected : undefined,
            column.selectable ? ColumnClasses.selectable : undefined,
            `anj-datatype-${column.dataType}`
        ];
    }
    static generateColumnName(field, caption) {
        const name = field ? field : caption ? caption.split(' ').join('-') : `anj-anon-${colId++}`;
        return name.toLowerCase();
    }
    static renderCell(data, column) {
        if (!utils.hasValue(data[column.field])) {
            return '';
        }
        switch (column.dataType) {
            case 'boolean':
                return booleanRenderer(data[column.field]);
            case 'date':
                return dateRenderer(data[column.field], column);
            case 'datetime':
                return datetimeRenderer(data[column.field], column);
            case 'number':
                return numberRenderer(data[column.field], column);
            default:
                return typeof data[column.field] === 'string' ? `${data[column.field].substring(0, 999)}` : `${data[column.field]}`;
        }
    }
    static renderEdit(data, column) {
        const translator = this.translator || ColumnRenderer.translator;
        const attrs = ColumnRenderer.validationAttrs(column.rules);
        const placeholder = ColumnRenderer.renderHeader(column.field, column.caption);
        if (column.options) {
            return (core.h("anj-form-group", null,
                core.h("anj-select", Object.assign({}, attrs, { placeholder: placeholder, name: column.field, value: data[column.field] }), column.options.options.map(o => core.h("anj-option", { value: column.options.valueKey ? o[column.options.valueKey] : o }, column.options.displayKey ? o[column.options.displayKey] : o)))));
        }
        switch (column.dataType) {
            case 'boolean':
                const label = data[column.field]
                    ? `${translator(Translations.DESELECT)}: ${column.name}`
                    : `${translator(Translations.SELECT)}: ${column.name}`;
                return core.h("anj-checkbox", { solo: true, checked: data[column.field], name: column.field, "aria-label": label });
            case 'date':
                return (core.h("anj-form-group", null,
                    core.h("anj-input", Object.assign({}, attrs, { placeholder: placeholder, name: column.field, value: dateRenderer(data[column.field], column) }),
                        core.h("anj-date-picker-toggle", null),
                        core.h("anj-date-picker", null))));
            case 'datetime':
                return (core.h("anj-form-group", null,
                    core.h("anj-input", Object.assign({}, attrs, { placeholder: placeholder, name: column.field, value: datetimeRenderer(data[column.field], column) }),
                        core.h("anj-datetime-picker-toggle", null),
                        core.h("anj-datetime-picker", null))));
            default:
                const type = attrs.type ? attrs.type : column.dataType === 'string' ? 'text' : column.dataType;
                const value = utils.hasValue(data[column.field]) ? data[column.field] : '';
                return (core.h("anj-form-group", null,
                    core.h("anj-input", Object.assign({}, attrs, { placeholder: placeholder, name: column.field, type: type, value: value }))));
        }
    }
    static validationAttrs(rules) {
        const attrs = {};
        rules.forEach(rule => {
            switch (rule.type) {
                case 'required':
                    attrs['required'] = true;
                    break;
                case 'email':
                    attrs['type'] = 'email';
                    break;
                default:
                    attrs[rule.type] = rule.value;
            }
        });
        return attrs;
    }
    static renderHeader(field, caption) {
        return caption ? caption : ColumnRenderer.fieldToCaption(field);
    }
    static fieldToCaption(field) {
        return field ? field.split(/(?=[A-Z])/).join(' ').replace(/_/g, ' ') : '';
    }
    async contextMenu() {
        if (!this.column.pinnable)
            return undefined;
        const options = await this.column.table.columnMenu();
        const updated = options.map(o => {
            o.disabled = o.action === this.column.pinned;
            return o;
        });
        return updated.length > 0 ? updated : undefined;
    }
    async setOffset(offset) {
        this.cells().forEach((cell) => this.setCellOffset(cell, offset));
    }
    async setWidth(width) {
        this.column.width = width;
        this.cells().forEach((cell) => this.setCellWidth(cell));
    }
    async initCell(cell, offset) {
        if (!cell) {
            return;
        }
        this.setCellOffset(cell, offset);
        if (this.column.width !== 'auto') {
            this.setCellWidth(cell);
        }
    }
    cells() {
        return Array.from(this.column.table.querySelectorAll(`.${ColumnRenderer.classFromColumnName(this.column.name)}`));
    }
    setCellOffset(cell, offset) {
        switch (this.column.pinned) {
            case 'left':
                cell.style.left = offset ? offset : `${this.calculateOffset(cell)}px`;
                break;
            case 'right':
                cell.style.right = offset ? offset : `${this.calculateOffset(cell, true)}px`;
                break;
            default:
                cell.style.left = '';
                cell.style.right = '';
                break;
        }
    }
    setCellWidth(cell) {
        cell.style.minWidth = this.column.width === 'auto' || this.column.width === '0' ? '' : this.column.width;
        cell.style.maxWidth = this.column.width === 'auto' || this.column.width === '0' ? '' : this.column.width;
        cell.style.width = this.column.width;
    }
    calculateOffset(cell, isRight = false) {
        let offset = 0;
        const pinned = Array.from(cell.parentElement.querySelectorAll(`.${ColumnRenderer.classFromPinned(this.column.pinned)}`));
        if (isRight) {
            pinned.reverse();
        }
        for (let i = 0; i < pinned.length; i++) {
            if (pinned[i] === cell) {
                break;
            }
            offset = offset + pinned[i].offsetWidth;
        }
        return offset;
    }
}
ColumnRenderer.translator = (s, _v) => s;
const booleanRenderer = (value) => {
    return value ? core.h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "18", height: "18", viewBox: "0 0 18 18" },
        core.h("path", { d: "M6.61 11.89L3.5 8.78 2.44 9.84 6.61 14l8.95-8.95L14.5 4z" })) : '';
};
const datetimeRenderer = (value, column) => {
    const dateValue = new Date(value);
    return dateValue.valueOf() ? column.table.datetimeFormatter(dateValue) : '';
};
const dateRenderer = (value, column) => {
    const dateValue = new Date(value);
    return dateValue.valueOf() ? column.table.dateFormatter(dateValue) : '';
};
const numberRenderer = (value, column) => {
    if (!utils.hasValue(value))
        return '';
    if (isNaN(value))
        return value;
    return !isNaN(value) ? column.table.numberFormatter(value) : value;
};

exports.COLUMN_CONTEXT_MENU = COLUMN_CONTEXT_MENU;
exports.ColumnRenderer = ColumnRenderer;
exports.FILTER_TYPES = FILTER_TYPES;
