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

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

        function sendInstanceNew(sCryps, name, players) {
            if (sCryps.length) {
                return ws.sendInstanceNew(sCryps, name, players);
            }
            return false;
        }

        return {
            sendInstanceNew,
            selectedCryps,
        };
    }
);

class InstanceCreateForm extends Component {
    constructor(props) {
        super(props);

        this.state = { players: 2, name: '' };

        const { sendInstanceNew } = props;

        this.sendInstanceNew = sendInstanceNew.bind(this);

        this.nameChange = this.nameChange.bind(this);
        this.playersChange = this.playersChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    playersChange(event) {
        this.setState({ players: Number(event.target.value) });
    }

    nameChange(event) {
        this.setState({ name: event.target.value });
    }

    handleSubmit(event) {
        event.preventDefault();
        this.sendInstanceNew(this.props.selectedCryps, this.state.name, this.state.players);
        this.setState({ name: '', players: 2 });
    }

    render() {
        const disabled = !this.props.selectedCryps.every(c => c);

        const classes = `create-form ${disabled ? 'disabled' : ''}`;
        return (
            <div className={classes}>
                <form>
                    <label>instance name</label>
                    <input
                        className="login-input"
                        type="text"
                        disabled={disabled}
                        value={this.state.name}
                        placeholder="name"
                        onChange={this.nameChange}
                    />
                    <label htmlFor="playerSelect">players</label>
                    <select id="playerSelect"
                        disabled={disabled}
                        value={this.state.players}
                        onChange={this.playersChange}
                        >
                        <option value={1}>pve</option>
                        <option value={2}>2</option>
                        <option value={4}>4</option>
                        <option value={8}>8</option>
                        <option value={16}>16</option>
                    </select>
                </form>
                <button
                    onClick={this.handleSubmit}
                    disabled={disabled}
                    type="submit">
                    +
                </button>
            </div>
        );
    }
}

module.exports = addState(InstanceCreateForm);
