package com.r3944realms.leashedplayer.mixin.server;

import com.mojang.authlib.GameProfile;
import com.r3944realms.leashedplayer.modInterface.ServerPlayerCapacity;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@SuppressWarnings("AddedMixinMembersNamePattern")
@Mixin(ServerPlayer.class)
public abstract class MixinServerPlayer extends Player implements ServerPlayerCapacity {
    @Shadow protected abstract void completeUsingItem();

    @Unique
    int Lp$TalkArea;
    @Unique
    int Lp$TalkAreaPreference;

    public MixinServerPlayer(Level pLevel, BlockPos pPos, float pYRot, GameProfile pGameProfile) {
        super(pLevel, pPos, pYRot, pGameProfile);
    }

    @Override
    public void setTalkArea(int talkArea) {
        Lp$TalkArea = talkArea;
    }

    @Override
    public int getTalkArea() {
        return Lp$TalkArea;
    }

    @Override
    public void setTalkAreaPreference(int talkAreaPreference) {
        Lp$TalkAreaPreference = talkAreaPreference;
    }

    @Override
    public int getTalkAreaPreference() {
        return Lp$TalkAreaPreference;
    }
    @Inject(method = {"tick()V"}, at = {@At("TAIL")})
    private void tick(CallbackInfo callbackInfo) {

    }
    @Inject(method = {"<init>"}, at = {@At("TAIL")})
    private void init(CallbackInfo callbackInfo) {
        this.Lp$TalkArea = -1;
        this.Lp$TalkAreaPreference = -1;
    }

    /**
     * 在玩家死亡后重生时，将旧玩家的数据恢复到当前玩家对象上
     */
    @Inject(method = {"restoreFrom"}, at = {@At("TAIL")})
    private void restoreFrom(ServerPlayer serverPlayer, boolean pKeepEverything, CallbackInfo callbackInfo) {
        Lp$TalkArea = ((ServerPlayerCapacity)serverPlayer).getTalkArea();
        Lp$TalkAreaPreference = ((ServerPlayerCapacity)serverPlayer).getTalkAreaPreference();
    }


    @Inject(method = {"readAdditionalSaveData"}, at = {@At("RETURN")})
    private void readSaveData(CompoundTag compoundTag, CallbackInfo callbackInfo) {
        if(compoundTag.contains("Lp$TalkArea")) {
            setTalkArea(compoundTag.getInt("Lp$TalkArea"));
        }
        if(compoundTag.contains("Lp$TalkAreaPreference")) {
            setTalkAreaPreference(compoundTag.getInt("Lp$TalkAreaPreference"));
        }
    }
    @Inject(method = {"addAdditionalSaveData"}, at = {@At("RETURN")})
    private void addSaveData(CompoundTag compoundTag, CallbackInfo callbackInfo) {
        compoundTag.putInt("Lp$TalkArea", Lp$TalkArea);
        compoundTag.putInt("Lp$TalkAreaPreference", Lp$TalkAreaPreference);
    }
}
