package com.shanebeestudios.skbee.elements.other.expressions;

import ch.njol.skript.aliases.ItemType;
import ch.njol.skript.classes.Changer.ChangeMode;
import ch.njol.skript.lang.Expression;
import com.github.shanebeee.skr.Registration;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;
import ch.njol.util.coll.CollectionUtils;
import com.shanebeestudios.skbee.api.skript.base.PropertyExpression;
import com.shanebeestudios.skbee.api.util.BlockDataUtils;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import org.bukkit.event.Event;
import org.bukkit.inventory.meta.BlockDataMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class ExprBlockDataItemTag extends PropertyExpression<ItemType, Object> {

    public static void register(Registration reg) {
        reg.newPropertyExpression(ExprBlockDataItemTag.class, Object.class,
                "item [block[ ]](data|state) tag %string%", "itemtypes")
            .name("BlockData - Item BlockData Tag")
            .description("Get/set the value of a tag in the BlockData of an item.")
            .examples("")
            .since("3.4.0")
            .register();
    }

    private Expression<String> tag;

    @SuppressWarnings("unchecked")
    @Override
    public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
        this.tag = (Expression<String>) exprs[matchedPattern];
        setExpr((Expression<ItemType>) exprs[1 - matchedPattern]);
        return true;
    }

    @Override
    protected Object[] get(Event event, ItemType[] source) {
        return get(source, itemType -> {
            if (!(itemType.getItemMeta() instanceof BlockDataMeta meta)) return null;

            Material blockForm = BlockDataUtils.getBlockForm(itemType.getMaterial());
            if (blockForm == null || !blockForm.isBlock()) return null;

            BlockData blockData = meta.getBlockData(blockForm);

            return BlockDataUtils.getBlockDataValueFromTag(blockData, this.tag.getSingle(event));
        });
    }

    @Override
    public Class<?> @Nullable [] acceptChange(ChangeMode mode) {
        if (mode == ChangeMode.SET) return CollectionUtils.array(Object.class);
        return null;
    }

    @Override
    public void change(Event event, @Nullable Object[] delta, ChangeMode mode) {
        if (delta == null) return;
        String tag = this.tag.getSingle(event);
        if (tag == null) {
            error("No tag found: " + this.tag.toString(event, true));
            return;
        }
        for (ItemType itemType : getExpr().getAll(event)) {
            Material blockForm = BlockDataUtils.getBlockForm(itemType.getMaterial());
            if (blockForm == null || !blockForm.isBlock()) continue;

            BlockDataMeta itemMeta = (BlockDataMeta) itemType.getItemMeta();
            BlockData oldBlockData = itemMeta.getBlockData(blockForm);

            BlockData newBlockData = BlockDataUtils.setBlockDataTag(oldBlockData, tag, delta[0]);
            if (newBlockData == null) {
                tagError("Invalid tag \"" + tag + "\" for this blockdata: " + oldBlockData.getAsString());
                continue;
            }
            itemMeta.setBlockData(newBlockData);
            itemType.setItemMeta(itemMeta);
        }
    }

    @Override
    public @NotNull Class<?> getReturnType() {
        return Object.class;
    }

    @Override
    public @NotNull String toString(Event e, boolean d) {
        return "item blockdata tag " + this.tag.toString(e, d) + " of " + getExpr().toString(e, d);
    }

    private void tagError(String message) {
        errorRegex(message, "tag \\\"\\w+\\\"");
    }

}
