import { __assign, __read, __spreadArray } from "tslib";
import React, { useState, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import SnackBar from "../SnackBar";
import { SnackBarWrapper } from "../../styles";
import store from "./store";
var CONTAINER_SNACK_BAR = "yggdrassil-snack-bar";
export var SnackBarInstance = function () {
    var _a = __read(useState([]), 2), snackBarList = _a[0], setSnackBarList = _a[1];
    var refInstance = useRef(null);
    var element = document.getElementById(CONTAINER_SNACK_BAR);
    if (!element) {
        element = document.createElement("div");
        element.setAttribute("id", CONTAINER_SNACK_BAR);
        document.body.appendChild(element);
    }
    useEffect(function () {
        if (process.env.NODE_ENV !== "production" &&
            element &&
            element.children.length > 1) {
            window.console.error("Warning: You are using two instances SnackBarInstance. Use only one instance per application.");
        }
    }, []);
    useEffect(function () {
        store.subscribe(updateSnackBarList);
        return function () {
            store.unsubscribe(updateSnackBarList);
            element === null || element === void 0 ? void 0 : element.remove();
        };
    }, []);
    var updateSnackBarList = function () {
        setSnackBarList(__spreadArray([], __read(store.data), false));
    };
    return createPortal(React.createElement(SnackBarWrapper, { ref: refInstance },
        React.createElement(TransitionGroup, { component: null, appear: true, enter: true, exit: true }, snackBarList.map(function (params) { return (React.createElement(CSSTransition, { key: params.id, mountOnEnter: true, unmountOnExit: true, classNames: "snack-bar", in: true, timeout: 300 },
            React.createElement(SnackBar, { id: params.id, message: params.message, action: params.action, count: params.count }))); }))), element);
};
export function openSnackBar(params) {
    var id = store.data.length + 1;
    store.add(__assign(__assign({}, params), { id: params.id || id }));
}
