/*
 *  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.compat;

import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModList;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.eroticdungeongame.EroticDungeon;
import top.r3944realms.eroticdungeongame.api.workspace.Services;
import top.r3944realms.eroticdungeongame.content.block.ISeatBlock;
import top.r3944realms.eroticdungeongame.content.block.blockentity.BaseSeatBlockEntity;
import top.r3944realms.eroticdungeongame.content.item.DeviceKeyItem;
import top.r3944realms.lib39.core.compat.ICompat;
import tschipp.carryon.common.carry.CarryOnData;
import tschipp.carryon.common.carry.CarryOnDataManager;
import tschipp.carryon.events.EntityPickupEvent;

public class CarryOnCompat implements ICompat {
    public static CarryOnCompat INSTANCE = new CarryOnCompat();
    public static ResourceLocation ID = EroticDungeon.rl("carryon");
    public boolean initialize = false;
    @Override
    public void setInitialize(boolean initialize) {
        this.initialize = initialize;
    }

    @Override
    public boolean isInitialized() {
        return initialize;
    }

    @Override
    public ResourceLocation id() {
        return ID;
    }

    @Override
    public boolean isModLoaded() {
        return ModList.get().isLoaded("carryon");
    }

    @Override
    public void initialize() {

    }

    @Override
    public void addCommonGameListener(@NotNull IEventBus gameBus) {
        gameBus.addListener(EventPriority.HIGHEST, this::onCarry);
        gameBus.addListener(EventPriority.HIGHEST, this::onPickUpEvent);
    }

    private void onCarry(PlayerInteractEvent.@NotNull RightClickBlock event) {
        if (!event.isCanceled()) {
            Player player = event.getEntity();
            Level level = event.getLevel();
            BlockPos pos = event.getPos();
            if (!level.isClientSide) {
                CarryOnData carry = CarryOnDataManager.getCarryData(player);
                if (carry.isCarrying(CarryOnData.CarryType.PLAYER)) {
                    if (!player.getPassengers().isEmpty() && player.getPassengers().get(0) instanceof Player carried) {
                        carried.unRide();
                        BlockState blockState = level.getBlockState(pos);
                        if (blockState.getBlock() instanceof ISeatBlock seatBlock) {
                            boolean success = seatBlock.bindPlayerToSeat(level, pos, blockState, carried);
                            if (success) {
                                event.setCanceled(true);
                            }
                        }
                    }
                }
            }
        }
    }
    private void onPickUpEvent(@NotNull EntityPickupEvent event) {
        if (!event.isCanceled() && !event.player.level().isClientSide()) {
            Boolean shouldCancelled = Services.WORK_SPACE.tryToDoIfInDeviceAndRet(event.target, i -> {
                if (event.player.level().getBlockEntity(i.getDeviceMainBlockPos()) instanceof BaseSeatBlockEntity seat) {
                    if (!seat.hasLockCode()) {
                        return false;
                    }
                    ItemStack itemInHand = event.player.getItemInHand(InteractionHand.MAIN_HAND);
                    return !DeviceKeyItem.isMatch(itemInHand, seat.getLockCode());
                }
                return false;
            }, () -> false);
            if (shouldCancelled) {
                event.setCanceled(true);
                event.player.displayClientMessage(Component.translatable("eroticdungeongame.message.quit.failed.locked").withStyle(ChatFormatting.RED), true);
            }
        }
    }
}
