package com.luticate.utils.dbo;

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

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

/**
 *
 * Created by robin on 11/27/15.
 */
public class LuMultipleDbo<T extends LuDbo> extends LuDbo {

    public List<T> getData() {
        return _data;
    }

    public void setData(List<T> data) {
        _data = data;
    }

    public int getCount() {
        return _count;
    }

    public void setCount(int count) {
        _count = count;
    }

    private List<T> _data = new Vector<>();

    private int _count;

    @Override
    public void fromJson(JSONObject json) throws JSONException {
        _count = json.getInt("Count");
        JSONArray array = json.getJSONArray("Data");
        for (int i = 0; i < array.length(); ++i) {
            try {
                T dbo = (T)((Class)((ParameterizedType)this.getClass().
                        getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
                dbo.fromJson(array.getJSONObject(i));
                _data.add(dbo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public HashMap<String, Object> toArray() {
        HashMap<String, Object> array = new HashMap<>();
        array.put("Count", _count);
        Vector<HashMap<String, Object>> data = new Vector<>();
        for (T value : _data) {
            data.add(value.toArray());
        }
        array.put("Data", data);
        return array;
    }
}
