package com.tiedup.remake.v2.bondage.component;

import com.google.gson.JsonObject;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.jetbrains.annotations.Nullable;

public enum ComponentType {
    LOCKABLE("lockable", LockableComponent::fromJson),
    RESISTANCE("resistance", ResistanceComponent::fromJson),
    GAGGING("gagging", GaggingComponent::fromJson),
    BLINDING("blinding", BlindingComponent::fromJson),
    SHOCK("shock", ShockComponent::fromJson),
    GPS("gps", GpsComponent::fromJson),
    CHOKING("choking", ChokingComponent::fromJson),
    ADJUSTABLE("adjustable", AdjustableComponent::fromJson),
    OWNERSHIP("ownership", OwnershipComponent::fromJson),
    BUILT_IN_LOCK("built_in_lock", BuiltInLockComponent::fromJson);

    private final String jsonKey;
    private final Function<JsonObject, IItemComponent> factory;

    /** Pre-built lookup map for O(1) fromKey() instead of linear scan. */
    private static final Map<String, ComponentType> BY_KEY;
    static {
        Map<String, ComponentType> map = new HashMap<>();
        for (ComponentType type : values()) {
            map.put(type.jsonKey, type);
        }
        BY_KEY = Collections.unmodifiableMap(map);
    }

    ComponentType(
        String jsonKey,
        Function<JsonObject, IItemComponent> factory
    ) {
        this.jsonKey = jsonKey;
        this.factory = factory;
    }

    public String getJsonKey() {
        return jsonKey;
    }

    public IItemComponent create(JsonObject config) {
        return factory.apply(config);
    }

    @Nullable
    public static ComponentType fromKey(String key) {
        return BY_KEY.get(key);
    }
}
