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.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;

import javax.annotation.Nonnull;

public class TpaHereCommand extends AbstractPlayerCommand {

    @Nonnull
    private final RequiredArg<PlayerRef> targetPlayerArg;

    public TpaHereCommand() {
        super("tpahere", "Asks another player to teleport them to you");
        this.targetPlayerArg = this.withRequiredArg("targetPlayer",
                "Player you want to teleport to you", 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 requester,
                           @NonNullDecl World world) {
        PlayerRef targetPlayerRef = this.targetPlayerArg.get(ctx);

        if (targetPlayerRef.getUuid().equals(requester.getUuid())) {
            requester.sendMessage(Message.raw("You can't teleport to yourself!"));
            return;
        }

        Ref<EntityStore> targetRef = targetPlayerRef.getReference();
        if (targetRef == null || !targetRef.isValid()) {
            requester.sendMessage(Message.raw("Player not found!"));
            return;
        }

        TpaRequestComponent tpaRequestComp = new TpaRequestComponent();
        tpaRequestComp.setRequester(requester.getUuid());
        tpaRequestComp.setType(TpaRequestComponent.RequestType.TPA_HERE);
        tpaRequestComp.setCreatedAt(System.currentTimeMillis());

        world.execute(() -> {
            store.addComponent(targetRef, HyStuff.TPA_REQUEST_COMPONENT_TYPE, tpaRequestComp);
        });

        targetPlayerRef.sendMessage(Message.raw(String.format(
            "[%s -> %s] %s has sent you a teleport request",
            targetPlayerRef.getUsername(),
            requester.getUsername(),
            requester.getUsername()
        )));

        requester.sendMessage(Message.raw(String.format(
            "Teleport request to %s sent successfully",
            targetPlayerRef.getUsername()
        )));
    }
}
