package com.kekenzy.model.sqlite.biz;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

import com.kekenzy.model.sqlite.bean.MapPosBean;
import com.kekenzy.model.sqlite.bean.RunningBean;
import com.kekenzy.model.sqllite.helper.MapPosTB;
import com.kekenzy.model.sqllite.helper.RunningDbHelper;
import com.kekenzy.model.sqllite.helper.RunningTB;

public class RunningDBManager {

	static final String TAG = "RunningDBManager";
	private SQLiteDatabase mDb;
	RunningDbHelper helper;

	MapPosTB mTB;
	RunningTB rTB;

	public RunningDBManager(Context context){
		if (helper == null) {
			helper = new RunningDbHelper(context);
		}

		try{
			mDb = helper.getWritableDatabase();
		}catch ( SQLiteException e) {
	        Log.d(TAG, e.toString());
			mDb = helper.getReadableDatabase();
		}
		mTB = new MapPosTB();
		rTB = new RunningTB();
	}

	public String[] RunningTbColumn(){
		return helper.getRunnningTBColumnList();

	}

	public long insertRun(RunningBean rBean){
		ContentValues values = new ContentValues();
		values.put(rTB.run_date.getName(), rBean.getRunDate());
		values.put(rTB.distance.getName(), rBean.getDistance());
		values.put(rTB.time.getName(), rBean.getTime());
		long id = mDb.insert(rTB.getTableName(), null, values);
		return id;
	}

	public long insertMapPos(MapPosBean mBean){
		ContentValues values = new ContentValues();
		values.put(mTB.run_id.getName(), mBean.getRunID());
		values.put(mTB.longitude.getName(), mBean.getLongitude());
		values.put(mTB.latitude.getName(), mBean.getLatitude());
		long id = mDb.insert(mTB.getTableName(), null, values);
		return id;
	}

	public void deleteRunByID(String id){
		mDb.delete(rTB.getTableName(), rTB.id.getName() + "=?", new String[] {id});
	}

	public void deleteMapPosByID(String id){
		mDb.delete(mTB.getTableName(), mTB.id.getName() + "=?", new String[] {id});
	}

	public void deleteAllRun(){
		mDb.delete(rTB.getTableName(), null, null);
	}

	public void deleteAllMapPos(){
		mDb.delete(mTB.getTableName(), null, null);
	}

	public Cursor fetchAllRun(){
		Cursor c = mDb.query(rTB.getTableName(),
				rTB.getColumnList(),
				null,	// where
				null,	// like
				null,	// group y
				null,		// having
				"_id DESC",	// orderd by
				null );
		return c;
	}

	public Cursor fetchAllMapPos(){
		Cursor c = mDb.query(mTB.getTableName(),
				mTB.getColumnList(),
				null,	// where
				null,	// like
				null,	// group y
				null,		// having
				"_id DESC",	// orderd by
				null );
		return c;
	}

	public void close(){
		mDb.close();
	}

}
