const Phaser = require('phaser');
const { POSITIONS: { COMBAT } } = require('./constants');

const CRYP_MARGIN = COMBAT.crypMargin();
const BOX_HEIGHT = CRYP_MARGIN * 0.8;
const BOX_WIDTH = COMBAT.width() * 0.2;


class CrypHitBox extends Phaser.GameObjects.Rectangle {
    constructor(scene, iter, team, cback) {
        const y = COMBAT.y() + COMBAT.height() * 0.05 + CRYP_MARGIN * iter;
        super(scene, (COMBAT.width() - BOX_WIDTH) * team, y, BOX_WIDTH, BOX_HEIGHT, 0x222222);
        this.setOrigin(0);
        this.clickHandler = () => cback();
    }

    select() {
        this.setFillStyle(0x003300);
    }

    deselect() {
        this.setFillStyle(0x222222);
    }
}

class CombatHitBox extends Phaser.Scene {
    constructor() {
        super({ key: 'CombatHitBox' });
    }

    create(phase) {
        this.phase = phase;
        this.registry.events.off('changedata', this.updateData);
        this.registry.events.on('changedata', this.updateData, this);
        if (phase === 'animating') return true;
        this.selectHitBox(phase);
        return true;
    }

    updateData(parent, key, data) {
        if (key === 'game' && data) {
            // In the case that we hit skill phase but teams change we restart
            if (data.teams.length !== this.teams) this.scene.restart(data.phase);
        }
        if (key === 'gamePhase' && data) {
            const shouldUpdate = data !== this.phase;
            if (shouldUpdate) this.scene.restart(data);
            return false;
        }
        return true;
    }

    selectHitBox(phase) {
        const game = this.registry.get('game');
        this.teams = game.teams.length;
        if (phase === 'Skill') return this.skillHitBox(game);
        return false;
    }

    skillHitBox(game) {
        const account = this.registry.get('account');
        const group = this.scene.get('CombatCryps').cryps;
        const skillScene = this.scene.get('CombatSkills');
        game.teams.forEach((t) => {
            t.cryps.forEach((c) => {
                const cback = () => {
                    const { activeSkill } = skillScene;
                    if (activeSkill) {
                        this.scene.get('CombatSkills').clearCrypActive(activeSkill.cryp.id);
                        activeSkill.activate();
                        skillScene.activeSkill = null;
                        this.game.events.emit('SEND_SKILL', game.id, activeSkill.cryp.id, c.id, activeSkill.skill.skill);
                    }
                };
                const crypSpawn = group.children.entries.find(s => s.cryp.id === c.id);
                const team = c.account === account.id ? 0 : 1;
                if (crypSpawn) this.add.existing(new CrypHitBox(this, crypSpawn.iter, team, cback));
            });
        });
        this.scene.moveBelow('Combat');
    }

    cleanUp() {
        this.registry.events.off('changedata', this.updateData);
        this.scene.remove();
    }
}

module.exports = CombatHitBox;
