package com.mq.mylibrary.db.grain_type;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.mq.mylibrary.db.BaseDao;
import com.mq.mylibrary.tool.HappySQL;
import com.mq.mylibrary.tool.LogTool;

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


/**
 * 创建人 mQ
 * 创建时间 2019/8/16 0016 10:30
 * 文件名称 CarDao
 * 说明:
 **/
public class GrainTypeDao extends BaseDao<GrainTypeEntity> {

    private GrainTypeDao() {
    }

    private static class SingleHelper {
        private static final GrainTypeDao INSTANCE = new GrainTypeDao();
    }

    public static GrainTypeDao get() {
        return SingleHelper.INSTANCE;
    }


    @Override
    public String getTableName() {
        return "grain_type";
    }


    public boolean insertByJSONArray(SQLiteDatabase db, JSONArray array) {
        if (array == null || array.length() == 0) {
            LogTool.i("初始化: 没有粮油品种信息");
            return true;
        }
        try {
            for (int i = 0; i < array.length(); i++) {
                long flg = insertByJSONObject(db, array.getJSONObject(i));
                if (flg == -1)
                    return false;
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }

    public long insertByJSONObject(SQLiteDatabase db, JSONObject object) {
        GrainTypeEntity entity = new GrainTypeEntity();
        entity.setGrain_id(object.optString("EnumItemId"));
        entity.setGrain_name(object.optString("EnumItemName"));
        entity.setParent_id(object.optString("EnumId"));
        return insert(db, entity);
    }

    public GrainTypeEntity getGrain(SQLiteDatabase db, String grain_id) {
        Cursor cursor = db.rawQuery("select * from " + getTableName() +
                " where grain_id = '" + grain_id + "'", null);
        return (GrainTypeEntity) HappySQL.cursor2VO(cursor, GrainTypeEntity.class);
    }


}
