/*
 *  Copyright 2025-2026 R3944Realms
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package top.r3944realms.eroticdungeongame.core.network.toServer;

import net.minecraft.ChatFormatting;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraftforge.network.NetworkEvent;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.eroticdungeongame.api.workspace.Services;
import top.r3944realms.eroticdungeongame.content.block.blockentity.BaseSeatBlockEntity;
import top.r3944realms.eroticdungeongame.util.IEDGEntity;

import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;

public record RequestQuitDevicePacket(Optional<Long> code, Optional<UUID> otherPlayer){
    public RequestQuitDevicePacket(@NotNull FriendlyByteBuf buf) {
        this(
                buf.readOptional(FriendlyByteBuf::readLong),
                buf.readOptional(FriendlyByteBuf::readUUID)
        );
    }
    public void encode(@NotNull FriendlyByteBuf buf) {
        buf.writeOptional(code, FriendlyByteBuf::writeLong);
        buf.writeOptional(otherPlayer, FriendlyByteBuf::writeUUID);
    }

    public void handle(@NotNull Supplier<NetworkEvent.Context> context) {
        context.get().enqueueWork(() -> {
            Player player = null;
            Player sender = context.get().getSender();
            boolean isSelf = false;
            if (otherPlayer.isPresent()) {
                if (sender != null) {
                    Level level = sender.level();
                    player = level.getPlayerByUUID(otherPlayer.get());
                }
            }
            if (player == null) {
                player = sender;
                isSelf = true;
            }
            if (player != null) {

                if (isSelf) {
                    Player finalPlayer = player;
                    if (player.isCreative()) {
                        Services.WORK_SPACE.tryToDoIfInDevice(player, i -> ((IEDGEntity)finalPlayer).releaseEntityFromEDGDevice());
                    } else {
                        Services.WORK_SPACE.tryToDoIfInDevice(player, i -> {
                            if(sender.level().getBlockEntity(i.getDeviceMainBlockPos()) instanceof BaseSeatBlockEntity seat) {
                                if (!seat.hasLockCode()) {
                                    ((IEDGEntity)finalPlayer).releaseEntityFromEDGDevice();
                                } else if (code.isPresent() && Objects.equals(seat.getLockCode(), code.get())) {
                                    ((IEDGEntity)finalPlayer).releaseEntityFromEDGDevice(code.get());
                                } else {
                                    finalPlayer.displayClientMessage(Component.translatable("eroticdungeongame.message.quit.failed.locked").withStyle(ChatFormatting.RED), true);
                                }
                            }
                        });

                    }
                } else {
                    if (!Services.WORK_SPACE.isInDevice(sender)) {
                        Player finalPlayer = player;
                        Services.WORK_SPACE.tryToDoIfInDevice(player, i -> {
                            if(sender.level().getBlockEntity(i.getDeviceMainBlockPos()) instanceof BaseSeatBlockEntity seat) {
                                if (!seat.hasLockCode()) {
                                    ((IEDGEntity)finalPlayer).releaseEntityFromEDGDevice();
                                } else if (code.isPresent() && Objects.equals(seat.getLockCode(), code.get())) {
                                    ((IEDGEntity)finalPlayer).releaseEntityFromEDGDevice(code.get());
                                } else {
                                    sender.displayClientMessage(Component.translatable("eroticdungeongame.message.quit.failed.locked").withStyle(ChatFormatting.RED), true);
                                }
                            }
                        });
                    }
                }
            }

        });
        context.get().setPacketHandled(true);
    }
}
