package net.miarma.hystuff.commands.teleport;

import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.CommandContext;
import com.hypixel.hytale.server.core.command.system.arguments.system.RequiredArg;
import com.hypixel.hytale.server.core.command.system.arguments.types.ArgTypes;
import com.hypixel.hytale.server.core.command.system.basecommands.AbstractPlayerCommand;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import com.hypixel.hytale.server.core.universe.Universe;
import com.hypixel.hytale.server.core.universe.world.World;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import net.miarma.hystuff.HyStuff;
import net.miarma.hystuff.component.TpaRequestComponent;
import org.checkerframework.checker.nullness.compatqual.NonNullDecl;

public class TpDenyCommand extends AbstractPlayerCommand {

    private final RequiredArg<PlayerRef> targetPlayerArg;

    public TpDenyCommand() {
        super("tpdeny", "Denies a teleport request");
        targetPlayerArg = this.withRequiredArg("targetPlayer",
                "Player you want to teleport to", ArgTypes.PLAYER_REF);
    }

    @Override
    protected boolean canGeneratePermission() {
        return false;
    }

    @Override
    protected void execute(@NonNullDecl CommandContext ctx,
                           @NonNullDecl Store<EntityStore> store,
                           @NonNullDecl Ref<EntityStore> ref,
                           @NonNullDecl PlayerRef playerRef,
                           @NonNullDecl World world) {
        PlayerRef targetPlayerRef = this.targetPlayerArg.get(ctx);
        Ref<EntityStore> targetRef = targetPlayerRef.getReference();
        if (targetRef == null || !targetRef.isValid()) {
            ctx.sendMessage(Message.translation("The target is no longer in the world."));
            return;
        }

        TpaRequestComponent tpa = store.getComponent(ref, HyStuff.TPA_REQUEST_COMPONENT_TYPE);
        if (tpa == null) {
            ctx.sendMessage(Message.raw(
                "You don't have pending teleport requests."
            ));
            return;
        }

        targetPlayerRef.sendMessage(Message.raw(String.format(
            "%s has denied your teleport request.",
            playerRef.getUsername()
        )));

        world.execute(() -> {
            store.removeComponent(ref, HyStuff.TPA_REQUEST_COMPONENT_TYPE);
        });

        ctx.sendMessage(Message.raw(String.format(
            "Teleport request from %s has been denied.",
            targetPlayerRef.getUsername()
        )));
    }
}
