package cn.net.caoyao.cpzshandset.db.dal.config;

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

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.db.ConfigDBHelper;

public class ConfigDal {
	private ConfigDBHelper helper;
	public ConfigDal(Context context) {
		helper = new ConfigDBHelper(context);
	}
	
	/**
	 * 插入设备ID到配置数据库中
	 * @param cBean
	 */
	public void insertConfig(ConfigBean cBean){
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "replace into hansetConfig(handsetMode,deviceId,status,expand1,expand2) values(?,?,?,?,?)";
		db.execSQL(sql, new Object[]{cBean.getHandsetMode(),cBean.getDeviceId(),cBean.getStatus(),cBean.getExpand1(),cBean.getExpand2()});
		db.close();
	}
	
	/**
	 * 查询本地存在的所有配置信息
	 * @return
	 */
	public List<ConfigBean> queryAllConfig(){
		List<ConfigBean> s = new ArrayList<>();
		SQLiteDatabase db = helper.getReadableDatabase();
		String sql = "select * from hansetConfig";
		Cursor c = db.rawQuery(sql, null);
		while (c.moveToNext()) {
			s.add(getConfigBean(c));
		}
		c.close();
		db.close();
		return s;
	}
	/**
	 * 根据手持机模式，查询对应的配置信息
	 * @param handsetMode:手持机的版本模式（其中的插入值对应于HandsetVersionConstant类中的值），主键，不能重复
	 * @return
	 */
	public ConfigBean queryConfigByHandsetMode(int handsetMode){
		ConfigBean b = null;
		SQLiteDatabase db = helper.getReadableDatabase();
		String sql = "select * from hansetConfig where handsetMode=?";
		Cursor c = db.rawQuery(sql, new String[]{String.valueOf(handsetMode)});
		if (c.moveToNext()) {
			b = getConfigBean(c);
		}
		c.close();
		db.close();
		return b;
	}

	private ConfigBean getConfigBean(Cursor c) {
		ConfigBean b = new ConfigBean();
		b.setHandsetMode(c.getInt(c.getColumnIndex("handsetMode")));
		b.setDeviceId(c.getString(c.getColumnIndex("deviceId")));
		b.setStatus(c.getInt(c.getColumnIndex("status")));
		b.setExpand1(c.getString(c.getColumnIndex("expand1")));
		b.setExpand2(c.getString(c.getColumnIndex("expand2")));
		return b;
	}

}
