/**
 * Контейнер-менеджер диалоговых окон, бережет память и нервы
 */

import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { block } from 'bem-cn';
import Modal from 'ui-components/lib/Modal';

import StoreMixin from 'lib/StoreMixin';
import ModalActions from 'actions/Modal';
import ModalStore from 'stores/Modals';

import './index.css';

const bModalBox = block('modal-box');

const ModalBox = React.createClass({

    mixins: [PureRenderMixin, StoreMixin],

    getStoreState() {
        return ModalStore.getState().toJS();
    },

    componentDidMount() {
        this.subscribe(ModalStore);
    },

    _handleClose() {
        const { onClose } = this.state;

        ModalActions.clear();

        if (onClose) {
            onClose();
        }
    },

    _renderContent() {
        const { component: Component, props, title } = this.state;
        let header = null;

        if (!Component) {
            return null;
        }

        if (title) {
            header = <h3 className={bModalBox('title')}>{title}</h3>;
        }

        return (
            <div className={bModalBox} aria-live="polite">
                {header}
                <div className={bModalBox('body')}>
                    <Component {...props} />
                </div>
                <div className={bModalBox('meta')}>
                    {`${window.ya.connect.initial.requestId} ${new Date().toISOString()}`}
                </div>
            </div>
        );
    },

    render() {
        const { visible, closable, mod } = this.state;

        return (
            <Modal
                closable={closable}
                mod={mod}
                onClose={this._handleClose}
                visible={visible}
            >
                {this._renderContent()}
            </Modal>
        );
    },

});

export default ModalBox;
