package org.forks.jsonrpc;

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

import org.json.JSONArray;
import org.json.JSONObject;

import static org.forks.jsonrpc.Helper.*;

public final class RpcPropertyMeta {
    private final String mName;
    private final String mType;
    private final Object mDefaultValue;

    public RpcPropertyMeta(String name, String type, Object defaultValue) {
        super();
        mName = name;
        mType = type;
        mDefaultValue = defaultValue;
    }

    public String getName() {
        return mName;
    }

    public String getType() {
        return mType;
    }

    public Object getDefaultValue() {
        return mDefaultValue;
    }

    static Map<String, RpcPropertyMeta> parse(JSONArray arr)
            throws JsonRpcException {
        Map<String, RpcPropertyMeta> result = new HashMap<String, RpcPropertyMeta>(
                arr.length());
        return parse(result, arr);
    }

    static Map<String, RpcPropertyMeta> parse(
            Map<String, RpcPropertyMeta> result, JSONArray arr)
            throws JsonRpcException {
        for (int i = 0; i < arr.length(); i++) {
            JSONObject item = getJsonObject(arr, i);
            RpcPropertyMeta prop = parse(item);
            result.put(prop.getName(), prop);
        }
        return result;
    }

    private static RpcPropertyMeta parse(JSONObject json)
            throws JsonRpcException {
        String name = getString(json, "name");
        String type = getString(json, "type");
        Object defaultValue = json.opt("defaultvalue");
        defaultValue = RpcTypeParser.fromJson(defaultValue, type);
        return new RpcPropertyMeta(name, type, defaultValue);
    }
}
