const preact = require('preact');
const { connect } = require('preact-redux');
const Phaser = require('phaser');
const PhaserCombat = require('./phaser.combat');

const addState = connect(
    function receiveState(state) {
        const { game, activeSkill, activeIncoming, account } = state;
        return {game, activeSkill, activeIncoming, account };
    }    
);

class PhaserInstance extends preact.Component {
    constructor(props) {
        super(props);
        this.props = props;
    }

    componentWillReceiveProps(nextProps) {
        const playerTeam = nextProps.game.teams.find(t => t.id === nextProps.account.id);
        const otherTeams = nextProps.game.teams.filter(t => t.id !== nextProps.account.id);
        if (playerTeam !== null && otherTeams !== null) {
            this.PhaserCombat.setPlayerOneHp(`${playerTeam.cryps[0].hp.value.toString()} / ${playerTeam.cryps[0].stam.value.toString()} HP`);
            this.PhaserCombat.setPlayerTwoHp(`${otherTeams[0].cryps[0].hp.value.toString()} / ${otherTeams[0].cryps[0].stam.value.toString()} HP`);

            if (playerTeam.cryps[0].hp.value === 0) {
                this.PhaserCombat.shootLeft();
            } else if (otherTeams[0].cryps[0].hp.value === 0) {
                this.PhaserCombat.shootRight();
            }
        }
    }

    componentDidMount() {
    // now mounted, can freely modify the DOM:
        this.PhaserCombat = new PhaserCombat();
        const config = {
            type: Phaser.DOM.FILL,
            width: 600,
            height: 400,
            parent: 'phaser-example',
            physics: {
                default: 'arcade',
                arcade: {
                    gravity: { y: 0 },
                },
            },
            scene: this.PhaserCombat,
        };
        const game = new Phaser.Game(config);
    }

    render() {
        return (
            <div id="phaser-example" style="overflow: hidden;">
            </div>
        );
    }
}
module.exports = addState(PhaserInstance);
