package eu.mhsl.minenet.minigames.instance.game.stateless.types.towerdefense;

import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.towerdefense.generator.MazeGenerator;
import eu.mhsl.minenet.minigames.util.BatchUtil;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.*;
import net.minestom.server.entity.attribute.Attribute;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import net.minestom.server.timer.TaskSchedule;

import java.util.List;
import java.util.UUID;

public class TowerdefenseRoom extends InstanceContainer {
    private final Player player;
    private final Towerdefense game;

    public TowerdefenseRoom(Player player, Towerdefense game) {
        super(UUID.randomUUID(), Dimension.OVERWORLD.key);
        MinecraftServer.getInstanceManager().registerInstance(this);
        this.player = player;
        this.game = game;
        this.player.setGameMode(GameMode.ADVENTURE);
        this.player.setAllowFlying(true);
        this.player.getInventory().setItemStack(0, ItemStack.of(Material.ARMOR_STAND));

        setGenerator(new MazeGenerator());
        BatchUtil.loadAndApplyBatch(this.game.getMazeBatch(), this, () -> {});
    }

    public void startWave(List<EntityType> entities) {
        int counter = 0;
        for(EntityType entityType : entities) {
            MinecraftServer.getSchedulerManager().scheduleTask(() -> {
                this.addEntity(new EntityCreature(entityType));
                return TaskSchedule.stop();
            }, TaskSchedule.millis(800L*counter));
            counter++;
        }
    }

    private void addEntity(EntityCreature entity) {
        entity.setInstance(this, this.game.getMazePath().getFirst());
        entity.getAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(0.15);
        entity.getNavigator().setPathTo(this.game.getMazePath().get(1), 0.7, () -> changeEntityGoal(entity, 1));
    }

    private void changeEntityGoal(EntityCreature entity, int positionIndex) {
        if(positionIndex == this.game.getMazePath().size()-1) {
            return;
        }
        entity.getNavigator().setPathTo(this.game.getMazePath().get(positionIndex+1), 0.7, () -> changeEntityGoal(entity, positionIndex+1));
    }

}
