import { Overlay } from '../overlay/Overlay.jsx';
import style from './dialog.css';

function Dialog ({closeOnEsc = true}, children) {
    function createHandlers (closeDialog) {
        function handleKeyDown ({which}) {
            (which === 27) && closeDialog();
        }

        return {
            onCreate () {
                document.addEventListener('keydown', handleKeyDown, true);
            },

            onRemove (element, done) {
                document.removeEventListener('keydown', handleKeyDown, true);
                done();
            }
        };
    }

    return function (state, actions) {
        if (!state.dialog.isOpen) {
            return null;
        }

        const closeDialog = actions.dialog.close;
        const elementHandlers = closeOnEsc ? createHandlers(closeDialog) : {};
        const {onCreate, onRemove} = elementHandlers;

        return (
            <Overlay oncreate={onCreate} onremove={onRemove} onBackgroundClick={closeDialog}>
                <button className={style.close} onclick={closeDialog} />

                <div className={style.content}>
                    {children}
                </div>
            </Overlay>
        );
    };
}

export {
    Dialog
};
