package eu.mhsl.minenet.minigames.instance;

import eu.mhsl.minenet.minigames.message.component.TranslatedComponent;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player;
import net.minestom.server.event.instance.AddEntityToInstanceEvent;
import net.minestom.server.event.instance.RemoveEntityFromInstanceEvent;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.instance.InstanceManager;
import net.minestom.server.registry.DynamicRegistry;
import net.minestom.server.timer.TaskSchedule;
import net.minestom.server.world.DimensionType;

import java.util.UUID;

public class MineNetInstance extends InstanceContainer {
    public MineNetInstance(DynamicRegistry.Key<DimensionType> type) {
        super(UUID.randomUUID(), type);
        MinecraftServer.getInstanceManager().registerInstance(this);

        eventNode()
                .addListener(AddEntityToInstanceEvent.class, this::onEntityAdd)
                .addListener(RemoveEntityFromInstanceEvent.class, this::onEntityRemove);
    }

    private void onEntityRemove(RemoveEntityFromInstanceEvent removeEntityFromInstanceEvent) {
        if(removeEntityFromInstanceEvent.getEntity() instanceof Player p) {
            this.onPlayerLeave(p);
        }
    }

    private void onEntityAdd(AddEntityToInstanceEvent addEntityToInstanceEvent) {
        if(addEntityToInstanceEvent.getEntity() instanceof Player p) {
            addEntityToInstanceEvent.setCancelled(this.onPlayerJoin(p));
        }
    }

    /**
     * Called when Player joins this instance
     * @param p player who is joining
     * @return setCanceled
     */
    protected boolean onPlayerJoin(Player p) {
        return false;
    }

    /**
     * Called when Player leaves this instance
     * @param p player who is leaving
     */
    protected void onPlayerLeave(Player p) {

    }

    /**
     *
     * @param target
     */
    public void destroy(Instance target) {
        getPlayers().forEach(player -> {
            if(target != null)
                player.setInstance(target);
            else
                player.kick(TranslatedComponent.byId("sample").getAssembled(player));
        });

        MinecraftServer.getSchedulerManager().scheduleTask(
                () -> MinecraftServer.getInstanceManager().unregisterInstance(this),
                TaskSchedule.seconds(10),
                TaskSchedule.stop()
        );
    }
}
