import Loot from "../prefabs/Loot";

const ITEM_SPACING = 80;
const DAMAGE_TYPES = [
    {
        color: '#FFFFFF',
        text: 'колющий'
    },
    {
        color: '#42EE26',
        text: 'острый'
    },
    {
        color: '#1948E1',
        text: 'магический'
    },
    {
        color: '#CF0000',
        text: 'заклинания'
    }
];

export default class Weakness extends Phaser.GameObjects.Layer {
    constructor(scene) {
        super(scene, []);

        this.scene = scene;
        this.scene.add.existing(this);
        this.add(this.scene.add.image(1080, 0, 'weakness')
            .setOrigin(0)
            .setScrollFactor(0)
        );
        this.add(this.scene.add.text(1140, 45, 'уязвимость', { fontSize: 36 }).setScrollFactor(0));
        this.add(this.scene.add.text(1140, 105, 'тип урона', { fontSize: 36 }).setScrollFactor(0));
        this.add(this.scene.add.text(1375, 105, 'колющий', { fontSize: 36, fontStyle: 'bold' }).setScrollFactor(0).setName('damageType'));
        this.init();
        this.show(this.scene.enemy.weakness, this.scene.enemy.damageType);
    }

    init() {
        this.scene.events.on('showWeakness', (items, enemyDamageType) => {
            this.show(items, enemyDamageType);
        });
        this.scene.events.on('hideWeakness', this.hide, this);

        this.items = this.scene.add.group({
            classType: Phaser.GameObjects.TileSprite,
            active: true,
            maxSize: 5
        });
    }

    createItem(itemId, position) {
        let item = this.items.getFirstDead();
        if (!item) {
            item = new Loot(
                this.scene,
                { x: 1425 + ITEM_SPACING * position, y: 60 },
                { width: 32, height: 32 },
                { texture: 'loot', frame: itemId }
            );

            this.items.add(item);
        }
        
        if (item.id !== itemId) item.setFrame(itemId);
        item.setScale(2.5).setActive(true).setVisible(true);
    }

    show(items, enemyDamageType) {
        this.setAlpha(1);
        for (let i = 0; i < items.length; i++) {
            this.createItem(items[i], i);
        }

        const damageTypeText = this.getByName('damageType');
        damageTypeText.setColor(DAMAGE_TYPES[enemyDamageType].color);
        damageTypeText.text = DAMAGE_TYPES[enemyDamageType].text;
    }

    hide() {
        const items = this.items.getChildren();
        for (let i = 0; i < items.length; i++) {
            this.items.killAndHide(items[i]);
        }
        this.setAlpha(0);
    }
}
