package nl.sbdeveloper.themeparkplus.util;

import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Directional;
import org.bukkit.block.data.Openable;
import org.jetbrains.annotations.NotNull;

public class LGUtil {
    private static final BlockData lampAanData = Bukkit.createBlockData(XMaterial.REDSTONE_LAMP.parseMaterial(), "lit=true");
    private static final BlockData lampUitData = Bukkit.createBlockData(XMaterial.REDSTONE_LAMP.parseMaterial(), "lit=false");

    private LGUtil() {}

    public static boolean zetLampAan(Block lampBlock) {
        if ((isLamp(lampBlock)) && (!isAan(lampBlock))) {
            lampBlock.setBlockData(lampAanData);
            return true;
        }
        return false;
    }

    public static boolean zetLampUit(Block lampBlock) {
        if ((isLamp(lampBlock)) && (isAan(lampBlock))) {
            lampBlock.setBlockData(lampUitData);
            return true;
        }
        return false;
    }

    public static boolean openGate(Block b) {
        return openGate(b, getDirection(b));
    }

    public static boolean openGate(Block b, BlockFace openFace) {
        BlockData blockData = b.getBlockData();
        if (isOpenable(b)) {
            Openable op = (Openable) blockData;
            if (op.isOpen()) return false;
            op.setOpen(true);
            b.setBlockData(blockData);

            Directional dir = (Directional) blockData;
            dir.setFacing(openFace);
            b.setBlockData(blockData);
            return true;
        }
        return false;
    }

    public static boolean closeGate(Block b) {
        BlockData blockData = b.getBlockData();
        if (isOpenable(b)) {
            Openable op = (Openable) blockData;
            if (!op.isOpen()) {
                return false;
            }
            op.setOpen(false);
            b.setBlockData(blockData);
            return true;
        }
        return false;
    }

    public static BlockFace getDirection(Block b) {
        BlockData blockData = b.getBlockData();
        if (isOpenable(b)) {
            Directional dir = (Directional) blockData;
            return dir.getFacing();
        }
        return null;
    }

    public static boolean isOpen(Block b) {
        BlockData blockData = b.getBlockData();
        if (isOpenable(b)) {
            Openable op = (Openable) blockData;
            return op.isOpen();
        }
        return false;
    }

    public static boolean isOpenable(@NotNull Block b) {
        return b.getBlockData() instanceof org.bukkit.block.data.Openable;
    }

    private static boolean isAan(Block lamp) {
        return lamp.getBlockData().getAsString().contains("lit=true");
    }

    private static boolean isLamp(Block lamp) {
        return lamp.getType() == XMaterial.REDSTONE_LAMP.parseMaterial();
    }
}