package com.yext.serialization.js;

import java.util.List;
import java.util.Map;

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

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * Helper class for dealing with json objects.
 *
 * @author Kevin Caffrey (kevin@yext.com)
 */
public class JsonUtil {
    /**
     * Converts a json object into a representation suitable for soy data.  Objects
     * are represented by maps, and arrays are represented by lists.  Primitives are
     * kept as-is.
     */
    public static Object jsonToSoyData(Object obj)
    throws JSONException {
        if (obj instanceof JSONObject) {
            // Convert the object to a map
            JSONObject json = (JSONObject)obj;
            Map<String, Object> map = Maps.newHashMap();
            JSONArray names = json.names();
            for (int i = 0; i < names.length(); i++) {
                String name = names.getString(i);
                map.put(name, jsonToSoyData(json.get(name)));
            }
            return map;
        } else if (obj instanceof JSONArray) {
            // Conver the object to an array list
            JSONArray array = (JSONArray)obj;
            List<Object> list = Lists.newArrayListWithExpectedSize(array.length());
            for (int i = 0; i < array.length(); i++) {
                list.add(jsonToSoyData(array.get(i)));
            }
            return list;
        } else {
            return obj;
        }
    }
}
