import { i18n } from 'arm-common';
import agui from 'arm-gui';
import React, { useCallback, useMemo } from 'react';
import { connect } from 'react-redux';


const selectorName = 'stub-gui-alive-status-message';

export default function AliveStatusMessage(props) {
    const { aliveStatus } = props;

    const reload = useCallback(() => {
        location.reload();
    }, [history])

    const showMessage = !aliveStatus.application || !aliveStatus.session;

    const text = useMemo(() => {
        if (!aliveStatus.session) {
            return {
                header: i18n(`CMA.ALIVE_STATUS.SESSION_EXPIRED`, 'Sessione scaduta'),
                messages: [
                    i18n(`CMA.ALIVE_STATUS.SESSION_EXPIRED.MSG.USER_DISCONNECTED`, 'Utente disconnesso.'),
                    i18n(`CMA.ALIVE_STATUS.SESSION_EXPIRED.MSG`, 'Per riconnettersi premere il tasto "Ricarica" oppure ricaricare la pagina.')
                ]
            };
        }
        return {
            header: i18n(`CMA.ALIVE_STATUS.APPLICATION_DOWN`, 'Applicazione non attiva'),
            messages: [
                i18n(`CMA.ALIVE_STATUS.APPLICATION_DOWN.NOT_AVAILABLE`, 'Applicazione momentaneamente non disponibile.'),
                i18n(`CMA.ALIVE_STATUS.APPLICATION_DOWN.MSG`, 'La preghiamo di contattare l\'amministratore, oppure ricaricare la pagina.')
            ]
        };
    }, [aliveStatus]);

    return (
        <agui.PopupDialog
            show={showMessage}
            className={selectorName}
            addBackDrop
            onClose={reload}
        >
            <agui.PopupDialog.Header>
                {text.header}
            </agui.PopupDialog.Header>

            <agui.PopupDialog.Body>
                <p>
                    {text.messages.map((message, index) => (
                        index === text.messages.length - 1 ?
                            <React.Fragment key={`${selectorName}-${index}`}>{message}</React.Fragment> :
                            <React.Fragment key={`${selectorName}-${index}`}>
                                {message}

                                <br />
                            </React.Fragment>
                    ))}
                </p>
            </agui.PopupDialog.Body>

            <agui.PopupDialog.Footer>
                <div style={{ marginLeft: 'auto' }} />

                <agui.aButton
                    bs='primary'
                    onClick={reload}
                >
                    {i18n(`CMA.SESSION_EXPIRED.RELOAD`, 'Ricarica')}
                </agui.aButton>
            </agui.PopupDialog.Footer>
        </agui.PopupDialog>
    );
}

const mapStateToProps = (state) => ({
    aliveStatus: state.account.aliveStatus
})

AliveStatusMessage = connect(mapStateToProps)(AliveStatusMessage);