package com.thebrokenrail.twine.block;

import com.thebrokenrail.twine.packet.OpenURLS2CPacket;
import com.thebrokenrail.twine.util.ItemUtil;
import com.thebrokenrail.twine.util.block.DirectionalBlock;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.block.BlockState;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.LecternBlockEntity;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;

import java.util.List;

@SuppressWarnings("deprecation")
public class CreativeURLOpenerBlock extends DirectionalBlock {
    public CreativeURLOpenerBlock() {
        super(Settings.of(Material.STONE).strength(-1.0F, 3600000.0F).dropsNothing());
    }

    @Override
    public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
        if (!world.isClient()) {
            BlockPos targetPos = pos.offset(state.get(FACING).getOpposite());
            BlockEntity entity = world.getBlockEntity(targetPos);
            if (entity instanceof LecternBlockEntity) {
                ItemStack stack = ((LecternBlockEntity) entity).getBook();

                Tag pages = stack.getOrCreateTag().get("pages");
                ListTag pagesList;
                if (pages instanceof ListTag) {
                    pagesList = (ListTag) pages;
                } else {
                    pagesList = new ListTag();
                }

                String url = pagesList.getString(((LecternBlockEntity) entity).getCurrentPage());
                if (stack.getItem() == Items.WRITTEN_BOOK) {
                    Text urlText = Text.Serializer.fromJson(url);
                    if (urlText != null) {
                        url = urlText.asString();
                    }
                }

                if (url.length() > 0) {
                    OpenURLS2CPacket.send((ServerPlayerEntity) player, url);
                }
            }
        }
        return ActionResult.SUCCESS;
    }

    @Override
    @Environment(EnvType.CLIENT)
    public void buildTooltip(ItemStack stack, BlockView world, List<Text> tooltip, TooltipContext options) {
        super.buildTooltip(stack, world, tooltip, options);
        ItemUtil.addTooltip("block", "creative_url_opener", 4, tooltip);
    }
}
