package kz.arta.synergy.workflow.mobile.android.files.offline.actions;

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

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by neox on 31.08.16.
 */
public class FilesRenameTable extends SQLiteOpenHelper {

    private SQLiteDatabase db = getWritableDatabase();
    private static final String TABLE_NAME = "FilesRenameTable";
    private static final String TABLE = "create table " + TABLE_NAME + " ("
            + "nodeID text,"
            + "newName text,"
            + "type text"
            + ");";

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

    public JSONArray get() {
        JSONArray jsonArray = new JSONArray();
        Cursor c = null;
        try {
            c = db.query(TABLE_NAME, null, null, null, null, null, null);
            if (c.moveToFirst()) {
                do {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("nodeID", c.getString(c.getColumnIndex("nodeID")));
                    jsonObject.put("newName", c.getString(c.getColumnIndex("newName")));
                    jsonObject.put("type", c.getString(c.getColumnIndex("type")));
                    jsonArray.put(jsonObject);
                } while (c.moveToNext());
            }
            return jsonArray;
        } catch (Exception exc) {
            return jsonArray;
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }
}