package top.r3944realms.lib39.core.command;

import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.core.command.model.CommandNode;
import top.r3944realms.lib39.core.command.model.Parameter;

import java.util.HashMap;
import java.util.Map;

/**
 * The type Simple command help manager.
 */
public abstract class SimpleCommandHelpManager implements ICommandHelpManager {
    private CommandNode root;
    private final Map<Integer, CommandNode> nodeCache = new HashMap<>();

    /**
     * Instantiates a new Simple command help manager.
     */
    public SimpleCommandHelpManager() {
       //
    }

    /**
     * 延遲初始化根節點
     */
    public void initialize() {
        if (root == null) {
            // 現在子類的字段已經初始化完成
            ResourceLocation id = getID();
            if (id == null) {
                throw new IllegalStateException("getID() must return non-null");
            }
            this.root = init();
        }
    }

    @Override
    public final @NotNull String getCommandHead() {
        return getID().getNamespace();
    }

    @Override
    public final Map<Integer, CommandNode> getCache() {
        return nodeCache;
    }
    @Override
    public void mergeTree(@NotNull CommandNode target, @NotNull CommandNode source) {
        // 合併參數
        for (Parameter param : source.getParameters()) {
            if (!target.getParameters().contains(param)) {
                target.addParameter(param.name(), param.required());
            }
        }

        // 合併子節點
        for (CommandNode sourceChild : source.getChildren()) {
            CommandNode targetChild = target.getChild(sourceChild.getName());
            if (targetChild == null) {
                target.addChild(sourceChild.deepCopy());
            } else {
                mergeTree(targetChild, sourceChild);
            }
        }
    }

    /**
     * 獲取根節點（如果未初始化則初始化）
     */
    @Override
    public final CommandNode getRootNode() {
        if (root == null) {
            initialize();
        }
        return root;
    }

    /**
     * 檢查是否已初始化
     *
     * @return the boolean
     */
    public boolean isInitialized() {
        return root != null;
    }
}
