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 SettingsTable extends SQLiteOpenHelper {

    private SQLiteDatabase db = getWritableDatabase();
    public static final String TABLE_NAME = "Settings";
    private static final String TABLE = "create table " + TABLE_NAME + " ("
            + "json text"
            + ");";

    public SettingsTable(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 insert(String json) {
        try {
            ContentValues cv = new ContentValues();
            cv.put("json", json);
            db.insert(TABLE_NAME, null, cv);
            return true;
        } catch (Exception exc) {
            return false;
        }
    }

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

    public String get() {
        String result = null;
        Cursor c = null;
        try {
            c = db.query(TABLE_NAME, null, null, null, null, null, null);
            if (c.moveToFirst()) {
                do {
                    result = c.getString(c.getColumnIndex("json"));
                } while (c.moveToNext());
            }
            return result;
        } catch (Exception exc) {
            return result;
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }
}
