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;

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

import kz.arta.synergy.workflow.mobile.android.common.models.LogSyncItem;

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

    private SQLiteDatabase db = getWritableDatabase();
    private static final String TABLE_NAME = "GetOfflineLogs";
    private static final String TABLE = "create table " + TABLE_NAME + " ("
            + "type text,"
            + "message text,"
            + "data text,"
            + "random text"
            + ");";

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

    public List<LogSyncItem> getMessages() {
        List<LogSyncItem> result = new ArrayList<>();
        Cursor c = null;
        try {
            c = db.query(TABLE_NAME, null, null, null, null, null, null);
            if (c.moveToFirst()) {
                do {
                    result.add(new LogSyncItem(c.getString(c.getColumnIndex("type")), c.getString(c.getColumnIndex("message")),
                            c.getString(c.getColumnIndex("data")), c.getString(c.getColumnIndex("random"))));
                } while (c.moveToNext());
            }
            return result;
        } catch (Exception exc) {
            return result;
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }
}
