package org.forks.jsonrpc;

import java.util.HashMap;

import android.util.SparseArray;

public final class NamedValue {

    private final short mValue;
    private final String mName;

    private NamedValue(short value, String name) {
        super();
        mValue = value;
        mName = name;
    }

    public short getValue() {
        return mValue;
    }

    public String getName() {
        return mName;
    }

    @Override
    public String toString() {
        return getName();
    }

    private static final HashMap<String, SparseArray<NamedValue>> sInstancePool = new HashMap<String, SparseArray<NamedValue>>();

    public static synchronized NamedValue create(String idtype, short val) {
        SparseArray<NamedValue> array = sInstancePool.get(idtype);
        if (array == null) {
            array = createArray(idtype);
            sInstancePool.put(idtype, array);
        }
        NamedValue result = array.get(val);
        if (result == null) {
            result = new NamedValue(val, Short.toString(val));
            array.put(val, result);
        }
        return result;
    }

    private static SparseArray<NamedValue> createArray(String idtype) {
        try {
            SparseArray<String> pairs = NamedValueMeta.get(idtype);
            SparseArray<NamedValue> result = new SparseArray<NamedValue>(
                    pairs.size());
            for (int i = 0; i < pairs.size(); i++) {
                int key = pairs.keyAt(i);
                NamedValue v = new NamedValue((short) key, pairs.valueAt(i));
                result.append(key, v);
            }
            return result;
        } catch (JsonRpcException e) {
            throw new JsonRpcRuntimeException(e);
        }
    }

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