"use strict";
/* eslint-disable jsx-a11y/control-has-associated-label */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
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 });
exports.Attach = void 0;
var react_1 = __importDefault(require("react"));
var bem_react_classname_1 = require("bem-react-classname");
var icons_classic_1 = require("@alfalab/icons-classic");
var cn_1 = require("../cn");
var button_1 = __importDefault(require("../button/button"));
var progress_bar_1 = __importDefault(require("../progress-bar"));
var MULTIPLE_TEXTS = ['файл', 'файла', 'файлов'];
/**
 * Возвращает слово в нужном склонении.
 *
 * @param number Количество
 * @param endingList Варианты слов, например: 'день', 'дня', 'дней'
 */
function getDeclension(number, endingList) {
    var endingIndex;
    number %= 100;
    if (number >= 11 && number <= 19) {
        endingIndex = 2;
    }
    else {
        switch (number % 10) {
            case 1:
                endingIndex = 0;
                break;
            case 2:
            case 3:
            case 4:
                endingIndex = 1;
                break;
            default:
                endingIndex = 2;
        }
    }
    return endingList[endingIndex];
}
/**
 * Производит поэлементное сравнение массивов.
 *
 * @param array1 Первый массив
 * @param array2 Второй массив
 */
function isEqualArray(array1, array2) {
    if (array1 === array2) {
        return true;
    }
    return array1
        && array2
        && array1.length === array2.length
        && array1.every(function (item, index) { return item === array2[index]; });
}
function isEmptyArray(value) {
    return Array.isArray(value) && !value.length;
}
/**
 * Компонент прикрепления файлов.
 */
var Attach = /** @class */ (function (_super) {
    __extends(Attach, _super);
    function Attach() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.cn = bem_react_classname_1.createCn('attach');
        _this.state = {
            focused: false,
            hovered: false,
            value: [],
        };
        _this.truncateFilename = function (filename) {
            var maxFilenameLength = _this.props.maxFilenameLength;
            if (maxFilenameLength && filename.length > maxFilenameLength) {
                var lengthOfPart = Math.round(maxFilenameLength / 2) - 1;
                return filename.substr(0, lengthOfPart) + "\u2026" + filename.substr(filename.length - lengthOfPart);
            }
            return filename;
        };
        _this.handleInputChange = function (event) {
            _this.performChange(Array.from(event.target.files), event);
        };
        _this.handleClearClick = function (event) {
            _this.input.value = '';
            _this.performChange([], event);
        };
        _this.handleButtonClick = function (event) {
            if (_this.props.onClick) {
                _this.props.onClick(event);
            }
        };
        _this.handleFocus = function (event) {
            _this.setState({ focused: true });
            if (_this.props.onFocus) {
                _this.props.onFocus(event);
            }
        };
        _this.handleBlur = function (event) {
            _this.setState({ focused: false });
            if (_this.props.onBlur) {
                _this.props.onBlur(event);
            }
        };
        _this.handleMouseEnter = function (event) {
            _this.setState({ hovered: true });
            if (_this.props.onMouseEnter) {
                _this.props.onMouseEnter(event);
            }
        };
        _this.handleMouseLeave = function (event) {
            _this.setState({ hovered: false });
            if (_this.props.onMouseLeave) {
                _this.props.onMouseLeave(event);
            }
        };
        return _this;
    }
    Attach.getDerivedStateFromProps = function (nextProps, prevState) {
        var nextValue = nextProps.value || [];
        if (!isEmptyArray(nextValue)
            && !isEqualArray(nextValue, prevState.value)) {
            return {
                value: nextValue,
            };
        }
        return null;
    };
    Attach.prototype.componentDidUpdate = function (_, prevState) {
        var nextValue = this.props.value || [];
        if (!isEqualArray(nextValue, prevState.value)) {
            this.input.value = '';
        }
    };
    Attach.prototype.render = function () {
        return (react_1.default.createElement("span", { className: this.cn({
                size: this.props.size,
                disabled: this.props.disabled,
                hovered: this.state.hovered,
                focused: this.state.focused,
            }), onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave, "data-test-id": this.props['data-test-id'] },
            this.renderButton(),
            this.renderStatusText()));
    };
    Attach.prototype.renderIcon = function () {
        switch (this.props.size) {
            case 's':
                return react_1.default.createElement(icons_classic_1.AttachmentSIcon, null);
            case 'l':
                return react_1.default.createElement(icons_classic_1.AttachmentLIcon, null);
            case 'xl':
                return react_1.default.createElement(icons_classic_1.AttachmentXlIcon, null);
            case 'm':
            default:
                return react_1.default.createElement(icons_classic_1.AttachmentMIcon, null);
        }
    };
    Attach.prototype.renderButton = function () {
        var _this = this;
        var buttonProps = __assign(__assign({}, this.props.buttonProps), { className: this.cn('button'), disabled: this.props.disabled, size: this.props.size, icon: this.props.icon ? this.props.icon : this.renderIcon(), focused: this.state.focused });
        return (react_1.default.createElement(button_1.default, __assign({}, buttonProps, { tag: "span", leftAddons: (react_1.default.createElement("label", { className: this.cn('label'), htmlFor: this.props.id },
                react_1.default.createElement("input", { ref: function (input) {
                        _this.input = input;
                    }, className: this.cn('control'), accept: this.props.accept, disabled: this.props.disabled, id: this.props.id, multiple: this.props.multiple, name: this.props.name, tabIndex: -1, type: "file", onChange: this.handleInputChange }))), tabIndex: this.props.tabIndex, onClick: this.handleButtonClick, onFocus: this.handleFocus, onBlur: this.handleBlur }), this.props.buttonContent));
    };
    Attach.prototype.renderStatusText = function () {
        var files = this.props.value === undefined ? this.state.value : (this.props.value || []);
        if (files && files.length > 0) {
            var content = (files.length === 1)
                ? this.truncateFilename(files[0].name)
                : (react_1.default.createElement("abbr", { title: files.map(function (file) { return file.name; }).join() },
                    files.length,
                    ' ',
                    getDeclension(files.length, MULTIPLE_TEXTS)));
            return (react_1.default.createElement("span", { className: this.cn('file') },
                react_1.default.createElement("span", { className: this.cn('text') }, content),
                react_1.default.createElement("button", { type: "button", className: this.cn('clear'), onClick: this.handleClearClick }),
                typeof this.props.progressBarPercent !== 'undefined' && (react_1.default.createElement(progress_bar_1.default, { percent: this.props.progressBarPercent, className: this.cn('progress-bar') }))));
        }
        return (react_1.default.createElement("span", { className: this.cn('no-file') }, this.props.noFileText));
    };
    /**
     * Ставит фокус на контрол.
     */
    Attach.prototype.focus = function () {
        this.input.focus();
    };
    /**
     * Убирает фокус с контрола.
     */
    Attach.prototype.blur = function () {
        this.input.blur();
    };
    Attach.prototype.performChange = function (value, event) {
        var _this = this;
        var shouldFireChange = !isEqualArray(value, this.state.value);
        this.setState({ value: value }, function () {
            if (_this.props.onChange && shouldFireChange) {
                _this.props.onChange(value.length ? value : null, event);
            }
        });
    };
    Attach.defaultProps = {
        buttonContent: 'Выберите файл',
        size: 'm',
        disabled: false,
        multiple: false,
        tabIndex: 0,
        noFileText: 'Нет файла',
    };
    return Attach;
}(react_1.default.PureComponent));
exports.Attach = Attach;
exports.default = cn_1.withTheme(Attach);

//# sourceMappingURL=attach.js.map
