package com.ym.modulecommon.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.ym.modulecommon.module.NewsEntity;

import org.apache.poi.hssf.record.formula.functions.T;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by fySpring
 * Date : 2017/5/10
 * To do :读取本地json文件
 */

public class JsonReadUtil {

    public static String getJsonStr(Context context, String fileName) {
        StringBuilder stringBuffer = new StringBuilder();
        AssetManager assetManager = context.getAssets();
        try {
            InputStream is = assetManager.open(fileName);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String str = null;
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return stringBuffer.toString();
    }


    public static <T> List<T> fromJsonFile(Context context, String fileName, Class<T> clazz) {
        String jsonStr = getJsonStr(context, fileName);

        List<T> lst = new ArrayList<T>();

        JsonArray array = new JsonParser().parse(jsonStr).getAsJsonArray();
        for (final JsonElement elem : array) {
            lst.add(new Gson().fromJson(elem, clazz));
        }

        return lst;
    }


    public static <T> List<T> fromJsonArray(String jsonStr, Class<T> clazz) {
        List<T> lst = new ArrayList<T>();
        try {

            JsonArray array = new JsonParser().parse(jsonStr).getAsJsonArray();
            for (final JsonElement elem : array) {
                lst.add(new Gson().fromJson(elem, clazz));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return lst;
    }

    public static List<NewsEntity> fromJson2New(String jsonStr) {
        ArrayList<NewsEntity> newsEntities = new ArrayList<>();

       LogUtils.d("huang========",jsonStr.toString());


        return newsEntities;
    }

    public static <T> List<T> jsonToDto(String message, String jsonHead,Class<T> cls){ //这里是Class<T>
        JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject();
        JsonArray jsonArray = jsonObject.getAsJsonArray(jsonHead);

        Gson gson = new Gson();
        List<T> list = new ArrayList<>();
        for (JsonElement jsonElement : jsonArray) {
            list.add(gson.fromJson(jsonElement,cls)); //cls
        }
        return list;
    }
}
