package com.bluedot.commons.utils;

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

public class JSONUtils
{
	public static boolean isValidJSON(String test)
	{
	    try 
	    {
	        new JSONObject(test);
	    } 
	    catch(JSONException ex) 
	    {
	        try 
	        {
	            new JSONArray(test);
	        } 
	        catch(JSONException ex1) 
	        {
	            return false;
	        }
	    }
	    return true;
	}
	
	public static JSONObject merge(JSONObject Obj1, JSONObject Obj2){
		if (Obj1==null && Obj2!=null)
			return new JSONObject(Obj2, JSONObject.getNames(Obj2));
		
		if (Obj1!=null && Obj2==null)
			return new JSONObject(Obj1, JSONObject.getNames(Obj1));
		
		if (Obj1==null && Obj2==null)
			return new JSONObject();
		
		JSONObject merged;
		
		if (JSONObject.getNames(Obj1)==null)
			merged = new JSONObject();
		else
			merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
		
		for(String key : JSONObject.getNames(Obj2))
		{
		  merged.put(key, Obj2.get(key));
		}
		return merged;
	}
	
	public static JSONObject createObjectList(JSONArray list, long rowCount, int page, int pageSize) {
		JSONObject result = new JSONObject();
		
		result.put("results", list);
		result.put("count", rowCount);
		result.put("page", page);
		result.put("pageSize", pageSize);
		
		return result;
	}
	
	public static JSONArray concatArray(JSONArray... arrs) throws JSONException {
	    JSONArray result = new JSONArray();
	    for (JSONArray arr : arrs) {
	        for (int i = 0; i < arr.length(); i++) {
	            result.put(arr.get(i));
	        }
	    }
	    return result;
	}
}
