package me.hammerle.supersnuvi.tiles;

import java.util.HashMap;
import me.hammerle.supersnuvi.javafx.Image;
import me.hammerle.supersnuvi.entity.Entity;
import me.hammerle.supersnuvi.gamelogic.StateRenderer;
import me.hammerle.supersnuvi.util.CollisionBox;
import me.hammerle.supersnuvi.util.Face;
import me.hammerle.supersnuvi.util.SoundUtils;
import me.hammerle.supersnuvi.util.Utils;

public class CrumblingStoneTile extends Tile
{
    private final Image[] images;
    
    private final HashMap<Long, Integer> states;
    
    public CrumblingStoneTile() 
    {
        states = new HashMap<>();
        images = new Image[47];
        for(int i = 0; i < 46; i++)
        {
            images[i] = Utils.getTileImage("crumbling_stones/crumbling_stones _frame" + (i + 1));
        }
        images[46] = StateRenderer.FALLBACK_TILE.getImage(0, 0);
        super.setCollisionBox(CollisionBox.createScaledBox(0, 0.4, 1, 1));
        super.setMovementBox(CollisionBox.createScaledBox(0, 0.4, 1, 1));
    }

    @Override
    public CollisionBox getMovementBox(int x, int y) 
    {
        int i = states.getOrDefault(getKey(x, y), 0) / 2;
        if(i >= 39)
        {
            return CollisionBox.NULL_BOX;
        }
        return super.getMovementBox(x, y);
    }

    @Override
    public void onEntityCollide(Entity ent, int x, int y, Face face) 
    {
        super.onEntityCollide(ent, x, y, face);
        if(face == Face.UP)
        {
            long key = getKey(x, y);
            if(!states.containsKey(key))
            {
                states.put(getKey(x, y), 0);
                SoundUtils.playSound(SoundUtils.Sound.STONE_CRUMBLING);
            }
        }
    }

    @Override
    public Image getImage(int x, int y) 
    {
        return images[states.getOrDefault(getKey(x, y), 0) / 2];
    }

    @Override
    public void tick() 
    {
        states.replaceAll((k, v) -> 
        {
            v++;
            if(v >= 94)
            {
                return 93;
            }
            return v;
        });
    }

    @Override
    public void reset() 
    {
        states.clear();
    } 
}
