package com.maxiee.heartbeat.database.api;

import android.content.Context;
import android.database.Cursor;

import com.maxiee.heartbeat.database.tables.EventsTable;
import com.maxiee.heartbeat.model.Event;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * Created by maxiee on 15-6-24.
 */
public class GetTodayEventApi extends BaseDBApi {

    public GetTodayEventApi(Context context) {
        super(context);
    }

    public ArrayList<Event> exec() {

        Calendar curDate = Calendar.getInstance();
        curDate.set(
                curDate.get(Calendar.YEAR),
                curDate.get(Calendar.MONTH),
                curDate.get(Calendar.DAY_OF_MONTH),
                0, 0
        );

        Cursor cursor = mDatabaseHelper.getReadableDatabase().query(
                EventsTable.NAME,
                new String[] {
                        EventsTable.ID,
                        EventsTable.EVENT,
                        EventsTable.TIMESTAMP
                },
                EventsTable.TIMESTAMP + ">?",
                new String[] {String.valueOf(curDate.getTimeInMillis())},
                null, null, null
        );

        if (cursor.getCount() < 1) {
            return null;
        }

        cursor.moveToFirst();
        ArrayList<Event> ret = new ArrayList<>();
        do {
            int id = cursor.getInt(
                    cursor.getColumnIndex(EventsTable.ID)
            );
            String event = cursor.getString(
                    cursor.getColumnIndex(EventsTable.EVENT)
            );
            long timestamp = cursor.getLong(
                    cursor.getColumnIndex(EventsTable.TIMESTAMP)
            );
            ret.add(0, new Event(
                    id,
                    event,
                    timestamp
            ));
        } while (cursor.moveToNext());

        cursor.close();

        return ret;
    }
}

@@ -1150,32 +1150,82 @@
 ull%0A        );%0A%0A
+        ArrayList%3CEvent%3E ret = new ArrayList%3C%3E();%0A
         if (curs
@@ -1241,24 +1241,52 @@
 nt() %3C 1) %7B%0A
+            cursor.close();%0A
             
@@ -1292,20 +1292,19 @@
  return 
-null
+ret
 ;%0A      
@@ -1342,58 +1342,8 @@
 ();%0A
-        ArrayList%3CEvent%3E ret = new ArrayList%3C%3E();%0A
     
@@ -1901,17 +1901,16 @@
 lose();%0A
-%0A
         

return empty list if has no data.