const { connect } = require('preact-redux');
const preact = require('preact');

const { saw } = require('./shapes');
const actions = require('../actions');

function pingColour(ping) {
    if (ping < 100) return 'forestgreen';
    if (ping < 200) return 'yellow';
    return 'red';
}

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            account,
            ping,
        } = state;

        function sendAccountStates() {
            ws.sendEmailState();
            ws.sendSubscriptionState();
        }

        return {
            sendAccountStates,
            account,
            ping,
        };
    },
    function receiveDispatch(dispatch) {
        function accountPage() {
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
            dispatch(actions.setActiveSkill(null));
            dispatch(actions.setInfo(null));
            dispatch(actions.setItemUnequip([]));
            return dispatch(actions.setNav('account'));
        }

        return {
            accountPage,
        };
    }
);


function AccountStatus(args) {
    const {
        account,
        ping,
        accountPage,
        sendAccountStates,
    } = args;

    if (!account) return null;

    function accountClick() {
        sendAccountStates();
        accountPage();
    }

    return (
        <div class="account-status">
            <div class="account-info">
                <h2 class="account-header">{account.name}</h2>
                {saw(pingColour(ping))}
                <div class="ping-text">{ping}ms</div>
            </div>
            <h3 class="account-header credits">{`¤${account.balance}`}</h3>
            <button onClick={accountClick}>⚙ account</button>
        </div>
    );
}

module.exports = addState(AccountStatus);
