import React from 'react';
import { connect } from 'react-redux';
import AppActions from '../../app/AppActions.js';


class Notify extends React.Component {
    constructor(props) {
        super(props);
        this.componentLog = (text, elem) => console.log("[Notify.jsx]: " + text, elem ? elem : null);
        this.closeNotifies = this.closeNotifies.bind(this);
    }

    closeNotifies(){
        let item = null;
        for (let key of this.props.listOfNotify.keys()) {
            item = this.props.listOfNotify.get(key)
            this.props.closeNotify(item.messageId);
        }
    }

    render() {
        this.componentLog("render", this);

        const { listOfNotify, closeNotify } = this.props;

        let myClass = "alert hidden";
        let message = "";
        let onClick = null;

        if (listOfNotify && listOfNotify !== null && listOfNotify.size > 0){
            let item = null;
            message = [];
            for (let key of listOfNotify.keys()) {
                item = listOfNotify.get(key)
                message.push(<div key={key} className={"alert-" + item.messageType.toLowerCase()}>{item.message}</div>);
            }
            myClass = "alert";
            onClick = this.closeNotifies;
        }

        return (
            <div className="notify">
                <div className={myClass} role="alert">
                    <button type="button" className="close" onClick={onClick}><i className="fa fa-times"/></button>
                    {message}
                </div>
            </div>
        );
    }
}


function mapStateToProps(state) {
    return {
        listOfNotify: state.app.listOfNotify
    };
}

function mapDispatchToProps(dispatch) {
    return {
        closeNotify: (index) => dispatch(AppActions.deleteNotify(index))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Notify);