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 android.os.AsyncTask;

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

import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.requests.RestClient;
import kz.arta.synergy.workflow.mobile.android.common.requests.SendGetRequest;
import kz.arta.synergy.workflow.mobile.android.common.utils.MyApplication;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkActionsItem;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkItem;

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

    private SQLiteDatabase db = getWritableDatabase();
    private static final String TABLE_NAME = "Actions";
    private static final String TABLE = "create table " + TABLE_NAME + " ("
            + "actionID text,"
            + "action text,"
            + "operation text,"
            + "label text,"
            + "color text"
            + ");";

    private Context context;
    private Person person;

    public WorkActionsTable(Context context) {
        super(context, TABLE_NAME, null, 1);
        this.context = context;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    @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 removeByActionID(String actionID) {
        try {
            db.delete(TABLE_NAME, "actionID = ?", new String[]{actionID});
            return true;
        } catch (Exception exc) {
            return false;
        }
    }

    public void removeWorksByArray(List<WorkItem> works) {
        try {
            for (WorkItem work : works) {
                db.delete(TABLE_NAME, "actionID = " + "\"" + work.getActionID() + "\"", null);
            }
        } catch (Exception exc) {
            // handling error ...
        }
    }

    public void add(String jsonString, String actionID) throws Exception {
        ContentValues cv = new ContentValues();
        WorkActionsItem[] item = RestClient.getGson().fromJson(jsonString, WorkActionsItem[].class);
        for (WorkActionsItem anItem : item) {
            cv.put("actionID", actionID);
            cv.put("action", anItem.getAction());
            cv.put("operation", anItem.getOperation());
            cv.put("label", anItem.getLabel());
            cv.put("color", anItem.getColor());
            db.insert(TABLE_NAME, null, cv);
            if (anItem.getAction().equals("RESULT")) {
                new GetResult(actionID).execute();
            }
        }
    }

    public List<WorkActionsItem> get(String actionID) {
        List<WorkActionsItem> result = new ArrayList<>();
        Cursor c = null;
        try {
            c = db.rawQuery("select * from " + TABLE_NAME + " where actionID = ?", new String[]{actionID});
            if (c.moveToFirst()) {
                do {
                    WorkActionsItem workActionsItem = new WorkActionsItem();
                    workActionsItem.setActionID(c.getString(c.getColumnIndex("actionID")));
                    workActionsItem.setAction(c.getString(c.getColumnIndex("action")));
                    workActionsItem.setOperation(c.getString(c.getColumnIndex("operation")));
                    workActionsItem.setLabel(c.getString(c.getColumnIndex("label")));
                    workActionsItem.setColor(c.getString(c.getColumnIndex("color")));
                    result.add(workActionsItem);
                } while (c.moveToNext());
            }
            return result;
        } catch (Exception exc) {
            return result;
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }

    class GetResult extends AsyncTask<Void, Void, String> {

        public String actionID;

        public GetResult(String actionID) {
            this.actionID = actionID;
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                WorkResultTable workResultTable = new WorkResultTable(context);
                workResultTable.insertResult(result, actionID);
            }
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            return new SendGetRequest(person).requestGET(person.getHost() +
                    "rest/api/workflow/work/completion_result?workID=" + actionID + "&locale=" + MyApplication.getLang());
        }
    }
}
