package com.fxy.utils;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;

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

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hasee on 2016/6/13.
 */
public class HttpDataUtils {

	public static final String str_datas = "datas";
	public static final String str_data = "rows";
    public static final String str_content = "content";

    /**
     * 获取JSONObject的JSONArray（key datas）
     * @param response
     * @return
     */
    public static JSONArray getJsonArrayByDatas(JSONObject response) {
        if (response == null)
            return null;
        return response.optJSONArray(str_datas);
    }

    /**
     * 获取JSONObject的JSONArray（key rows）
     * @param response
     * @return
     */
    public static JSONArray getJsonArrayByData(JSONObject response) {
        if (response == null)
            return null;
        return response.optJSONArray(str_data);
    }

    /**
     * 将JSONArray字符串转化为JSONArray
     * @param response
     * @return
     */
    public static JSONArray getJsonArrayByData(String response) {
        if (TextUtils.isEmpty(response))
            return null;
		try {
			return new JSONArray(response);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}


	/**
	 * 获取JSONObject的JSONArray（自定义key）
	 * @param response
	 * @return
	 */
	public static JSONArray getJsonArrayByData(JSONObject response, String txt) {
		if (response == null)
			return null;
		return response.optJSONArray(txt);
	}

    /**
     * 获取JSONObject的JSONArray（key content）
     * @param response
     * @return
     */
    public static JSONArray getJsonArrayByContent(JSONObject response) {
        if (response == null)
            return null;
        return response.optJSONArray(str_content);
    }
    
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> List<T> getList(JSONArray jsonArray, Class T) {
		try {
			if (jsonArray != null) {
				Log.d("HttpDataUtils","jsonArray: " + jsonArray.toString());
				List<T> list = JSON.parseArray(jsonArray.toString(), T);
				for (T t:list){
					Log.d("HttpDataUtils","t: " + t.toString());
				}
				if (list == null) {
					return new ArrayList<T>();
				} else {
					return list;
				}
			} else {
				return new ArrayList<T>();
			}
		} catch (Exception e) {
			return new ArrayList<T>();
		}
    }

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T> T getObject(JSONObject data, Class T) {
		T t = null;
		try {
			t = (T) JSON.parseObject(data.toString(), T);
		} catch (Exception e) {
			
		}
		return t;
	};

}
