package org.forks.jsonrpc;

import java.util.HashMap;
import java.util.List;

import android.util.SparseArray;

import static org.forks.jsonrpc.RpcFacade.toFullErtPathByPrefixedErt;

public final class NamedValueMeta {
    private static final String NAMED_VALUE_PAIR = "/sbin/NamedValuePair";
    private static final String METHOD = "/sbin/NamedValue/GetDefinition";
    private static final HashMap<String, SparseArray<String>> sCache = new HashMap<String, SparseArray<String>>();

    public static final class Pair {
        public final int Value;
        public final String Name;

        Pair(int value, String name) {
            super();
            Value = value;
            Name = name;
        }
    }

    public static final SparseArray<String> get(String idType)
            throws JsonRpcException {
        synchronized (sCache) {
            SparseArray<String> result = sCache.get(idType);
            if (result != null) {
                return result;
            }
        }

        SparseArray<String> result = doGet(idType);
        synchronized (sCache) {
            sCache.put(idType, result);
        }
        return result;
    }

    private static SparseArray<String> doGet(String idType)
            throws JsonRpcException {
        String methodPath = toFullErtPathByPrefixedErt(idType, METHOD);
        String rpcPath = toFullErtPathByPrefixedErt(idType, NAMED_VALUE_PAIR);

        JsonRpcResult res = RpcFacade.rpcCall(methodPath, idType);
        List<RpcObject> pairs = res.getRpcObjectList(rpcPath);
        return toNamedValueMap(pairs);
    }

    private static SparseArray<String> toNamedValueMap(List<RpcObject> pairs) {
        SparseArray<String> result = new SparseArray<String>(pairs.size());
        for (RpcObject pair : pairs) {
            Integer key = pair.getInt("Value");
            String value = pair.getString("Name");
            result.put(key, value);
        }
        return result;
    }

    static void reset() {
        sCache.clear();
    }

    static void register(String idType, SparseArray<String> names) {
        sCache.put(idType, names);
    }

    public static String toName(Short val, String namedValueType)
            throws JsonRpcException {
        if (val == null) {
            return "";
        }
        String idType = RpcTypeParser.getNamedValueTidType(namedValueType);
        SparseArray<String> names = get(idType);
        String result = names.get(val);
        if (result == null) {
            result = val.toString();
        }
        return result;
    }

}
