import React from "react";
import classes from "./classes.module.scss";
import ToastElement from "./ToastElement";
import classNames from "classnames";
import Toasts, { IToast } from "@Front/Stores/Toasts";

type IProps = {};
type IState = {
	toastList: IToast[];
};
export class ToastsContainerClass extends React.Component<IProps, IState> {
	private removeOnChange = () => {};

	public constructor(props: IProps) {
		super(props);
		this.state = {
			toastList: Toasts.getInstance().toasts,
		};

		this.updateToasts = this.updateToasts.bind(this);
	}

	public override render(): JSX.Element {
		return (
			<div className={classNames(classes["root"], this.state.toastList.length > 0 && classes["open"])}>
				<>
					{this.state.toastList.map((toast) => {
						return <ToastElement toast={toast} key={toast.id}/>;
					})}
				</>
			</div>
		);
	}

	public override componentDidMount() {
		this.removeOnChange = Toasts.getInstance().onChange(this.updateToasts);
	}

	public override componentWillUnmount() {
		this.removeOnChange();
	}

	private updateToasts(toastList: IToast[]) {
		this.setState({ toastList });
	}
}

export default function ToastsContainer(props: IProps) {
	return <ToastsContainerClass {...props}/>;
};
