package com.revoapp.calendar.database;

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

import com.revoapp.api.database.calendar.pojo.Pills;

import java.util.ArrayList;

public class PillsDatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 5;

    private static final String DATABASE_NAME = "calendar";

    private static final String TABLE_PILLS = "pills";

    private static final String COL_ID = "id";
    private static final String COL_NAME = "name";
    private static final String COL_COLOR = "color";
    private static final String COL_SHAPE = "shape";
    private static final String COL_QUANTITY = "quantity";
    private static final String COL_DESCRIBE = "describe";
    private static final String COL_DATETIME = "datetime";
    private static final String COL_TAKEN = "taken";
    private static final String COL_EXPIRED = "expired";

    private SQLiteDatabase db;

    public PillsDatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_PILLS_TABLE = "CREATE TABLE " + TABLE_PILLS + "("
                + COL_ID + " INTEGER PRIMARY KEY,"
                + COL_NAME + " TEXT,"
                + COL_COLOR + " INTEGER,"
                + COL_SHAPE + " INTEGER,"
                + COL_QUANTITY + " TEXT,"
                + COL_DESCRIBE + " TEXT,"
                + COL_DATETIME + " INTEGER,"
                + COL_TAKEN + " INTEGER,"
                + COL_EXPIRED + " INTEGER"
                + ")";

        db.execSQL(CREATE_PILLS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion == 2) {
            db.execSQL("ALTER TABLE " + TABLE_PILLS + " ADD COLUMN " + COL_TAKEN + " INTEGER DEFAULT 0");
        } else if (oldVersion == 3) {
            db.execSQL("ALTER TABLE " + TABLE_PILLS + " ADD COLUMN " + COL_EXPIRED + " INTEGER DEFAULT 0");
        } else {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_PILLS);
            onCreate(db);
        }
    }

    private void createDbObject() {
        db = this.getWritableDatabase();
    }

    public void dropDatabase() {
        if (db == null || !db.isOpen())
            createDbObject();
        db.execSQL("DROP TABLE " + TABLE_PILLS);

        onCreate(db);
    }

    public void addPill(Pills pills) {
        if (db == null || !db.isOpen())
            createDbObject();

        ContentValues values = new ContentValues();
        values.put(COL_ID, pills.getmId());
        values.put(COL_NAME, pills.getmPillName());
        values.put(COL_COLOR, pills.getmPillColor());
        values.put(COL_SHAPE, pills.getmPillShape());
        values.put(COL_QUANTITY, pills.getmQuantity());
        values.put(COL_DESCRIBE, pills.getmDescribe());
        values.put(COL_DATETIME, pills.getmDateTime());
        values.put(COL_TAKEN, pills.getmTaken());
        values.put(COL_EXPIRED, pills.getmExpired());

        db.insert(TABLE_PILLS, null, values);
        closeDB();
    }

    public void addPills(ArrayList<Pills> pills) {
        if (pills == null || pills.isEmpty())
            return;

        for (Pills p : pills)
            addPill(p);
    }

    public int takePill(int id) {
        if (db == null || !db.isOpen())
            createDbObject();

        ContentValues values = new ContentValues();
        values.put(COL_TAKEN, 1);

        int count = db.update(TABLE_PILLS, values, COL_ID + "=?", new String[]{Integer.toString(id)});
        closeDB();
        return count;
    }

    public int expirePill(int id) {
        if (db == null || !db.isOpen())
            createDbObject();

        ContentValues values = new ContentValues();
        values.put(COL_EXPIRED, 1);

        int count = db.update(TABLE_PILLS, values, COL_ID + "=?", new String[]{Integer.toString(id)});
        closeDB();
        return count;
    }

    public ArrayList<Pills> getAllPills(boolean onlyNotTaken) {
        ArrayList<Pills> pillsList = new ArrayList<Pills>();
        String selectQuery;
        if (onlyNotTaken)
            selectQuery = "SELECT * FROM " + TABLE_PILLS + " WHERE " + COL_TAKEN + "=0 AND " + COL_EXPIRED + "=0";
        else
            selectQuery = "SELECT * FROM " + TABLE_PILLS;

        if (db == null || !db.isOpen())
            createDbObject();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Pills pill = new Pills();
                if (cursor.getString(0) != null)
                    pill.setmId(Integer.parseInt(cursor.getString(0)));
                pill.setmPillName(cursor.getString(1));
                if (cursor.getString(2) != null)
                    pill.setmPillColor(Integer.parseInt(cursor.getString(2)));
                pill.setmPillShape(Integer.parseInt(cursor.getString(3)));
                pill.setmQuantity(cursor.getString(4));
                pill.setmDescribe(cursor.getString(5));
                pill.setmDateTime(cursor.getLong(6));
                pill.setmTaken(cursor.getInt(7));
                pill.setmExpired(cursor.getInt(8));

                pillsList.add(pill);
            } while (cursor.moveToNext());
        }

        cursor.close();
        closeDB();
        return pillsList;
    }

    public ArrayList<Pills> getAllPillsByDate(long beginDate, long endDate) {
        ArrayList<Pills> pillsList = new ArrayList<Pills>();
        String selectQuery = "SELECT * FROM " + TABLE_PILLS + " WHERE "
                + COL_DATETIME + " BETWEEN " + beginDate + " AND " + endDate;

        if (db == null || !db.isOpen())
            createDbObject();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Pills pill = new Pills();
                if (cursor.getString(0) != null)
                    pill.setmId(Integer.parseInt(cursor.getString(0)));
                pill.setmPillName(cursor.getString(1));
                if (cursor.getString(2) != null)
                    pill.setmPillColor(Integer.parseInt(cursor.getString(2)));
                pill.setmPillShape(Integer.parseInt(cursor.getString(3)));
                pill.setmQuantity(cursor.getString(4));
                pill.setmDescribe(cursor.getString(5));
                pill.setmDateTime(cursor.getLong(6));
                pill.setmTaken(cursor.getInt(7));
                pill.setmExpired(cursor.getInt(8));

                pillsList.add(pill);
            } while (cursor.moveToNext());
        }

        cursor.close();
        closeDB();
        return pillsList;
    }

    public int getPillsCount() {
        String countQuery = "SELECT " + COL_ID + " FROM " + TABLE_PILLS;
        if (db == null || !db.isOpen())
            createDbObject();
        Cursor cursor = db.rawQuery(countQuery, null);

        int count = cursor.getCount();
        cursor.close();

        closeDB();
        return count;
    }

    public boolean isEmpty() {
        return getPillsCount() <= 0;
    }

    public void deletePill(int id) {
        if (db == null || !db.isOpen())
            createDbObject();
        db.delete(TABLE_PILLS, COL_ID + "=?", new String[]{Integer.toString(id)});

        closeDB();
    }

    public void deleteAllPill() {
        if (db == null || !db.isOpen())
            createDbObject();
        db.delete(TABLE_PILLS, null, null);

        closeDB();
    }

    public void closeDB() {
        if (db != null && db.isOpen())
            db.close();
        this.close();
    }
}