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

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

        function sendInstanceNew(sConstructs, name, pve) {
            if (sConstructs.length) {
                return ws.sendInstanceNew(sConstructs, name, pve);
            }
            return false;
        }

        return {
            sendInstanceNew,
            team,
        };
    }
);

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

        this.state = { pve: false, name: '' };

        const { sendInstanceNew } = props;

        this.sendInstanceNew = sendInstanceNew.bind(this);

        this.nameInput = this.nameInput.bind(this);
        this.pveChange = this.pveChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    pveChange() {
        this.setState({ pve: !this.state.pve });
    }

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

    handleSubmit(event) {
        event.preventDefault();
        this.sendInstanceNew(this.props.team, this.state.name, this.state.pve);
        this.setState({ name: '', pve: false });
    }

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

        const classes = `create-form ${disabled ? 'disabled' : ''}`;
        return (
            <div class={classes}>
                <form>
                    <fieldset>
                        <legend>New Instance</legend>
                        <label>Instance Name</label>
                        <input
                            class="login-input"
                            type="text"
                            disabled={disabled}
                            value={this.state.name}
                            placeholder="game name"
                            onInput={this.nameInput}
                        />
                        <label htmlFor="pveSelect">Practice Mode - vs CPU, no Time Control</label>
                        <input id="pveSelect"
                            type="checkbox"
                            disabled={disabled}
                            checked={this.state.pve}
                            onChange={this.pveChange}
                            >
                        </input>
                    </fieldset>
                </form>
                <button
                    onClick={this.handleSubmit}
                    disabled={disabled}
                    type="submit">
                    +
                </button>
            </div>
        );
    }
}

module.exports = addState(InstanceCreateForm);
