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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import React from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { ThemeFactory } from '../../lib/theming/ThemeFactory.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { RenderContainer } from '../../internal/RenderContainer/index.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { isTestEnv } from '../../lib/currentEnvironment.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './Toast.styles.js';
import { ToastView } from './ToastView.js';
export var ToastDataTids = {
    toastStatic: 'StaticToast',
    toastView: 'ToastView__root',
    action: 'ToastView__action',
    close: 'ToastView__close',
};
/**
 * `Toast` — это короткое немодальное уведомление, которое сообщает пользователю о результате выполнения его команды.
 * Результат может быть положительным, отрицательным или нейтральным.
 *
 */
var Toast = /** @class */ (function (_super) {
    __extends(Toast, _super);
    function Toast(props) {
        var _this = _super.call(this, props) || this;
        _this.rootRef = React.createRef();
        /**
         * Показывает тост с `notification` в качестве сообщения.
         * Тост автоматически скрывается через 3 или 7 секунд,
         * в зависимости от наличия у него кнопки `action` внутри config-а.
         * Время показа можно задать вручную, передав `showTime` внутри config-а.
         *
         * @public
         * @param {React.ReactNode} notification
         * @param {ToastPushConfig} config объект с конфигурацией отображения компонента Toast
         */
        _this.push = function (notification, config) {
            if (_this.state.notification) {
                _this.close();
            }
            safelyCall(_this.props.onPush, notification, config === null || config === void 0 ? void 0 : config.action);
            _this.setState(function (_a) {
                var _b;
                var id = _a.id;
                return ({
                    notification: notification,
                    action: config === null || config === void 0 ? void 0 : config.action,
                    id: id + 1,
                    showTime: config === null || config === void 0 ? void 0 : config.showTime,
                    showCloseIcon: config === null || config === void 0 ? void 0 : config.showCloseIcon,
                    currentUse: (_b = config === null || config === void 0 ? void 0 : config.use) !== null && _b !== void 0 ? _b : 'default',
                });
            }, _this._setTimer);
        };
        /**
         * @public
         */
        _this.close = function () {
            safelyCall(_this.props.onClose, _this.state.notification, _this.state.action);
            _this.setState({ notification: null, action: null });
        };
        _this.setRootRef = function (element) {
            _this.setRootNode(element);
            // @ts-expect-error: See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31065.
            _this.rootRef.current = element;
        };
        _this._clearTimer = function () {
            if (_this._timeout) {
                clearTimeout(_this._timeout);
                _this._timeout = null;
            }
        };
        _this._setTimer = function () {
            var _a;
            _this._clearTimer();
            var showTime = _this.state.action ? 7000 : 3000;
            showTime = (_a = _this.state.showTime) !== null && _a !== void 0 ? _a : showTime;
            _this._timeout = setTimeout(_this.close, showTime);
        };
        _this._refToast = function (element) {
            _this._toast = element;
        };
        _this.state = {
            notification: null,
            action: null,
            id: 0,
            showTime: null,
            showCloseIcon: false,
            currentUse: 'default',
        };
        return _this;
    }
    Toast.prototype.componentWillUnmount = function () {
        this._clearTimer();
    };
    Toast.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = _this.props.theme ? ThemeFactory.create(_this.props.theme, theme) : theme;
            return (React.createElement(ThemeContext.Provider, { value: _this.theme },
                React.createElement(RenderContainer, null,
                    React.createElement(TransitionGroup, null, _this._renderToast()))));
        }));
    };
    Toast.prototype._renderToast = function () {
        var _a = this.state, notification = _a.notification, action = _a.action, id = _a.id, showCloseIcon = _a.showCloseIcon, currentUse = _a.currentUse;
        if (!notification) {
            return null;
        }
        var toastProps = {
            onMouseEnter: this._clearTimer,
            onMouseLeave: this._setTimer,
            onClose: this.close,
            children: notification,
            'aria-label': this.props['aria-label'],
            action: action,
            showCloseIcon: showCloseIcon,
            use: currentUse,
        };
        return (React.createElement(CSSTransition, { key: id, classNames: {
                enter: this.styles.enter(),
                enterActive: this.styles.enterActive(),
                exit: this.styles.exit(),
                exitActive: this.styles.exitActive(),
            }, timeout: {
                enter: 200,
                exit: 150,
            }, enter: !isTestEnv, exit: !isTestEnv, nodeRef: this.rootRef },
            React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootRef }, this.props),
                React.createElement(ToastView, __assign({ ref: this._refToast }, toastProps)))));
    };
    Toast.__KONTUR_REACT_UI__ = 'Toast';
    Toast.displayName = 'Toast';
    Toast = __decorate([
        withRenderEnvironment,
        rootNode
    ], Toast);
    return Toast;
}(React.Component));
export { Toast };
function safelyCall(fn) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
    }
    if (fn) {
        fn.apply(void 0, args);
    }
}
//# sourceMappingURL=Toast.js.map