package kz.arta.synergy.workflow.mobile.android.common.offline.get;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by neox on 04.07.14.
 */
public class WorkFiltersTable extends SQLiteOpenHelper {

    private SQLiteDatabase db = getWritableDatabase();
    private static final String TABLE_NAME = "Filters";
    private static final String TABLE = "create table " + TABLE_NAME + " ("
            + "key text,"
            + "value text"
            + ");";

    public WorkFiltersTable(Context context) {
        super(context, TABLE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {

    }

    public boolean removeAll() {
        try {
            db.delete(TABLE_NAME, null, null);
            return true;
        } catch (Exception exc) {
            return false;
        }
    }

    public boolean put(String key, String value) {
        try {
            ContentValues cv = new ContentValues();
            cv.put("key", key);
            cv.put("value", value);
            db.insert(TABLE_NAME, null, cv);
            return true;
        } catch (Exception exc) {
            return false;
        }
    }

    public String getFilter(String key) {
        String result = null;
        Cursor c = null;
        try {
            c = db.rawQuery("select * from " + TABLE_NAME + " where key = ?", new String[]{key});
            if (c.moveToFirst()) {
                result = c.getString(c.getColumnIndex("value"));
            }
            return result;
        } catch (Exception exc) {
            return null;
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }
}
