Autocomplete Feature für Kursnamen hinzugefügt (eigene API, da von DHBW nicht bereitg...
[DHBWCampusApp.git] / app / src / main / java / de / dhbwloe / campusapp / database / DatabaseManager.java
index 97875404cb33f58a0d0977a1e6f916c77ef9915d..628d78f88ff9728d0437e61b025539c68c44e029 100644 (file)
@@ -1,25 +1,31 @@
+/* DatabaseManager.java
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
 package de.dhbwloe.campusapp.database;
-
 import android.app.Activity;
 import android.content.ContentValues;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
-import android.util.Log;
 
-import net.fortuna.ical4j.model.DateList;
-import net.fortuna.ical4j.model.DateTime;
-import net.fortuna.ical4j.model.Period;
-import net.fortuna.ical4j.model.Recur;
-import net.fortuna.ical4j.model.parameter.Value;
-import net.fortuna.ical4j.model.property.RRule;
+import net.fortuna.ical4j.model.Component;
 
-import java.lang.reflect.Array;
-import java.text.ParseException;
 import java.util.ArrayList;
 import java.util.Date;
-import java.util.ListIterator;
 
 import de.dhbwloe.campusapp.CampusAppContext;
+import de.dhbwloe.campusapp.coursenames.CourseName;
 import de.dhbwloe.campusapp.mensaplan.MensaTagesplan;
 import de.dhbwloe.campusapp.news.NewsItem;
 import de.dhbwloe.campusapp.search.SearchIndices;
@@ -30,8 +36,9 @@ import de.dhbwloe.campusapp.vorlesungen.CourseGroup;
  * Created by pk910 on 19.01.2016.
  */
 public class DatabaseManager {
-    private static final String DATABASE_NAME = "DHBWLoe.CampusApp.DEV";
-    private static final int DATABASE_VERSION = 1;
+    private static final String DATABASE_NAME = "DHBWLoe.CampusApp.db";
+    private static final int DATABASE_VERSION = 3; // Datenbank Version - muss bei strukturellen Anpassungen erhöht werden
+
     private CampusAppContext AppContext;
     private SQLiteDatabase database;
     private NewsDatabaseHelper newsDBHelper;
@@ -43,10 +50,18 @@ public class DatabaseManager {
         AppContext = context;
     }
 
-    public void initializeDatabase() {
+    private void openDatabase() {
+        if(database != null)
+            return;
+
         database = AppContext.getMainActivity().openOrCreateDatabase(DATABASE_NAME, Activity.MODE_PRIVATE, null);
+    }
+
+    public void initializeDatabase() {
+        openDatabase();
         database.execSQL("CREATE TABLE IF NOT EXISTS Version(Version INT);");
 
+        // Abfragen der Datenbank Version
         Cursor resultSet = database.rawQuery("Select * from Version", null);
         int version;
         if(resultSet.moveToFirst()) {
@@ -57,14 +72,12 @@ public class DatabaseManager {
         }
 
         resultSet.close();
-        if(version < DATABASE_VERSION)
+        if(version < DATABASE_VERSION) // Upgrade der Datenbank Struktur (oder auch Initialisierung)
             upgradeTables(version, DATABASE_VERSION);
-
-
     }
 
     private void upgradeTables(int oldVersion, int newVersion) {
-        if(oldVersion == 0 && newVersion > 0) {
+        if(oldVersion == 0 && newVersion > 0) { // Initialisierung (noch keine Datenbank)
             database.execSQL("CREATE TABLE IF NOT EXISTS RuntimeCache " +
                     "(" +
                     "Reference TEXT, " +
@@ -81,6 +94,8 @@ public class DatabaseManager {
                     "StaticEntry INT, " +
                     "UpdateTime INT, " +
                     "TargetPage TEXT);");
+
+            // Vorlesungsplan
             database.execSQL("CREATE TABLE IF NOT EXISTS CourseCalendar " +
                     "(" +
                     "Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
@@ -105,14 +120,6 @@ public class DatabaseManager {
                     "PRIMARY KEY (EventId, EventFrom, EventTo)" +
                     ");");
             database.execSQL("CREATE INDEX CourseCalendarEventIdx ON CourseCalendarEvent (EventFrom, EventTo);");
-            database.execSQL("CREATE TABLE IF NOT EXISTS NfcCardStore " +
-                    "(" +
-                    "CardId INT, " +
-                    "UpdateTime INT," +
-                    "CardBalance INT, " +
-                    "CardLastTransaction INT, " +
-                    "PRIMARY KEY (CardId, UpdateTime)" +
-                    ");");
             database.execSQL("CREATE TABLE IF NOT EXISTS CourseCalendarGroup " +
                     "(" +
                     "GroupId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
@@ -122,6 +129,18 @@ public class DatabaseManager {
                     "UNIQUE (GroupName)" +
                     ");");
             database.execSQL("CREATE INDEX CourseCalendarGroupIdx ON CourseCalendarGroup (CourseName, GroupName);");
+
+            // Mensa Karten History is this actually used?)
+            database.execSQL("CREATE TABLE IF NOT EXISTS NfcCardStore " +
+                    "(" +
+                    "CardId INT, " +
+                    "UpdateTime INT," +
+                    "CardBalance INT, " +
+                    "CardLastTransaction INT, " +
+                    "PRIMARY KEY (CardId, UpdateTime)" +
+                    ");");
+
+            // Mensaplan
             database.execSQL("CREATE TABLE IF NOT EXISTS MensaPlan " +
                     "(" +
                     "PlanDate INT, " +
@@ -137,6 +156,8 @@ public class DatabaseManager {
                     "PriceSchool INT, " +
                     "PRIMARY KEY (PlanDate, MenuName)" +
                     ");");
+
+            // News
             database.execSQL("CREATE TABLE IF NOT EXISTS News " +
                     "(" +
                     "Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
@@ -155,13 +176,28 @@ public class DatabaseManager {
         }
         if(oldVersion < 2 && newVersion >= 2) {
             // Version 2
+            database.execSQL("ALTER TABLE CourseCalendarEvent ADD EventType INT;");
+        }
+        if(oldVersion < 3 && newVersion >= 3) {
+            // Version 3
+            database.execSQL("CREATE TABLE IF NOT EXISTS CourseNames " +
+                    "(" +
+                    "CourseName TEXT, " +
+                    "Status TEXT, " +
+                    "LastUpdate INT" +
+                    ");");
+        }
+        if(oldVersion < 4 && newVersion >= 4) {
+            // Version 4
 
         }
 
-        database.execSQL("UPDATE Version SET Version = "+Integer.toString(newVersion));
+        database.execSQL("UPDATE Version SET Version = " + Integer.toString(newVersion));
     }
 
     public void addSearchIndices(SearchIndices[] indices) {
+        // Hinzufügen oder Updaten mehrerer SearchIndice Objekte
+        openDatabase();
         for(int i = 0; i < indices.length; i++) {
             String[] whereArgs = new String[] {
                     indices[i].getKeyName()
@@ -195,6 +231,8 @@ public class DatabaseManager {
     }
 
     public SearchIndices[] performSearchRequest(String query, int maxResults) {
+        // App Suche
+        openDatabase();
         String[] whereArgs = new String[] {
                 "%" + query + "%"
         };
@@ -228,6 +266,8 @@ public class DatabaseManager {
     }
 
     public void setRuntimeCache(String name, String value) {
+        // Simple cache for runtime options
+        openDatabase();
         long now = (new Date()).getTime() / 1000;
         String[] whereArgs = new String[] {
                 name
@@ -261,6 +301,7 @@ public class DatabaseManager {
     }
 
     public String getRuntimeCache(String name) {
+        openDatabase();
         String value = null;
         String[] whereArgs = new String[] {
                 name
@@ -274,6 +315,7 @@ public class DatabaseManager {
     }
 
     public void addNfcCardData(NfcCardData nfcCardData) {
+        openDatabase();
         String[] whereArgs = new String[] {
                 Integer.toString(nfcCardData.getUniqueId()),
                 Long.toString(nfcCardData.getLastUpdate())
@@ -306,6 +348,7 @@ public class DatabaseManager {
     }
 
     public NfcCardData[] getNfcCardData(int lastLimit) {
+        openDatabase();
         String value = null;
         Cursor resultSet;
         if(lastLimit > 0) {
@@ -328,67 +371,203 @@ public class DatabaseManager {
         return resultsArr;
     }
 
-    public void updateCourseCalendar(CourseEvent event) {
+    public NfcCardData getLatestNfcCardData(int cardId) {
+        openDatabase();
+        String value = null;
+        String[] whereArgs = {
+                Integer.toString(cardId)
+        };
+        Cursor resultSet = database.rawQuery("SELECT CardId,UpdateTime,CardBalance,CardLastTransaction FROM NfcCardStore WHERE CardId = ? ORDER BY UpdateTime DESC LIMIT 1", whereArgs);
+        NfcCardData nfcCardData = null;
+        if(resultSet.moveToFirst()) {
+            nfcCardData = new NfcCardData(resultSet.getInt(0), resultSet.getLong(1), resultSet.getInt(2), resultSet.getInt(3));
+        }
+        resultSet.close();
+        return nfcCardData;
+    }
+
+    public CourseName[] getCourseNames() {
+        openDatabase();
+        String value = null;
+        Cursor resultSet;
+        resultSet = database.rawQuery("SELECT CourseName, Status, LastUpdate FROM CourseNames ORDER BY CourseName ASC", null);
+
+        ArrayList<CourseName> courseNames = new ArrayList<CourseName>();
+        if(resultSet.moveToFirst()) {
+            do {
+                CourseName cname = new CourseName(resultSet.getString(0), resultSet.getString(1), resultSet.getLong(2));
+                courseNames.add(cname);
+            } while (resultSet.moveToNext());
+        }
+        resultSet.close();
+        CourseName[] resultsArr = new CourseName[courseNames.size()];
+        resultsArr = courseNames.toArray(resultsArr);
+        return resultsArr;
+    }
+
+    public CourseName getLatestCourseName() {
+        openDatabase();
+        CourseName lastCourse = null;
+        Cursor resultSet;
+        resultSet = database.rawQuery("SELECT CourseName, Status, LastUpdate FROM CourseNames ORDER BY LastUpdate DESC LIMIT 1", null);
+
+        if(resultSet.moveToFirst()) {
+            lastCourse = new CourseName(resultSet.getString(0), resultSet.getString(1), resultSet.getLong(2));
+        }
+        resultSet.close();
+        return lastCourse;
+    }
+
+    public void addCourseName(CourseName courseName) {
+        openDatabase();
+        String[] whereArgs = new String[] {
+                courseName.getName()
+        };
+        Cursor resultSet = database.rawQuery("SELECT CourseName FROM CourseNames WHERE CourseName = ?", whereArgs);
+        if(resultSet.moveToFirst()) {
+            if(courseName.isActiveCourse()) {
+                try {
+                    ContentValues updateValues = new ContentValues();
+                    updateValues.put("Status", courseName.getStatus());
+                    updateValues.put("LastUpdate", courseName.getLastUpdate());
+
+                    database.update("CourseNames", updateValues, "CourseName = ?", whereArgs);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } else {
+                database.delete("CourseNames", "CourseName = ?", whereArgs);
+            }
+        } else if(courseName.isActiveCourse()) {
+            try {
+                ContentValues indexValues = new ContentValues();
+                indexValues.put("CourseName", courseName.getName());
+                indexValues.put("Status", courseName.getStatus());
+                indexValues.put("LastUpdate", courseName.getLastUpdate());
+
+                database.insertOrThrow("CourseNames", null, indexValues);
+            } catch(Exception e) {
+                e.printStackTrace();
+            }
+        }
+        resultSet.close();
+    }
+
+    public boolean haveCourseName(String courseName) {
+        openDatabase();
+        String[] whereArgs = new String[] {
+                courseName
+        };
+        Cursor resultSet = database.rawQuery("SELECT CourseName FROM CourseNames WHERE CourseName = ?", whereArgs);
+        boolean result;
+        if(resultSet.moveToFirst()) {
+            result = true;
+        } else {
+            result = false;
+        }
+        return result;
+    }
+
+    public void updateCourseCalendar(CourseEvent event, Component cevent) {
+        openDatabase();
         if(vorlesungsplanDBHelper == null)
             vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
-        vorlesungsplanDBHelper.updateCourseCalendar(event);
+        vorlesungsplanDBHelper.updateCourseCalendar(event, cevent);
     }
 
     public CourseEvent[] getCourseCalendarEvents(String coursename, long timeFrom, long timeTo) {
+        openDatabase();
         if(vorlesungsplanDBHelper == null)
             vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
         return vorlesungsplanDBHelper.getCourseCalendarEvents(coursename, timeFrom, timeTo);
     }
 
+    public CourseEvent[] getCourseEventsByGroup(CourseGroup group) {
+        openDatabase();
+        if(vorlesungsplanDBHelper == null)
+            vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
+        return vorlesungsplanDBHelper.getCourseEventsByGroup(group);
+    }
+
+    public CourseEvent[] getCourseCalendarTimetable(String coursename, long timeFrom, int days) {
+        openDatabase();
+        if(vorlesungsplanDBHelper == null)
+            vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
+        return vorlesungsplanDBHelper.getCourseCalendarTimetable(coursename, timeFrom, days);
+    }
+
     public CourseGroup getCourseGroup(int courseGroupId) {
+        openDatabase();
         if(vorlesungsplanDBHelper == null)
             vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
         return vorlesungsplanDBHelper.getCourseGroup(courseGroupId);
     }
 
     public CourseGroup getCourseGroup(String coursename, String groupname) {
+        openDatabase();
         if(vorlesungsplanDBHelper == null)
             vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
         return vorlesungsplanDBHelper.getCourseGroup(coursename, groupname);
     }
 
     public CourseGroup addCourseGroup(String coursename, String groupname) {
+        openDatabase();
         if(vorlesungsplanDBHelper == null)
             vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
         return vorlesungsplanDBHelper.addCourseGroup(coursename, groupname);
     }
 
+    public CourseGroup[] getCourseGroups(String coursename, Date notBefore) {
+        openDatabase();
+        if(vorlesungsplanDBHelper == null)
+            vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
+        return vorlesungsplanDBHelper.getCourseGroups(coursename, notBefore);
+    }
+
+    public CourseEvent[] getCourseExamEvents(String coursename, long timeFrom, long timeTo) {
+        openDatabase();
+        if(vorlesungsplanDBHelper == null)
+            vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
+        return vorlesungsplanDBHelper.getCourseExamEvents(coursename, timeFrom, timeTo);
+    }
+
     public void updateMensaTagesplan(MensaTagesplan plan) {
+        openDatabase();
         if(mensaplanDBHelper == null)
             mensaplanDBHelper = new MensaplanDatabaseHelper(AppContext, database);
         mensaplanDBHelper.updateMensaTagesplan(plan);
     }
 
     public MensaTagesplan[] getMensaTagesplan(long timeFrom, long timeTo) {
+        openDatabase();
         if(mensaplanDBHelper == null)
             mensaplanDBHelper = new MensaplanDatabaseHelper(AppContext, database);
         return mensaplanDBHelper.getMensaTagesplan(timeFrom, timeTo);
     }
 
     public long[] getDaysWithPlanData(long timeFrom, long timeTo) {
+        openDatabase();
         if(mensaplanDBHelper == null)
             mensaplanDBHelper = new MensaplanDatabaseHelper(AppContext, database);
         return mensaplanDBHelper.getDaysWithPlanData(timeFrom, timeTo);
     }
 
     public long[] getWeeksWithPlanData(long timeFrom, long timeTo) {
+        openDatabase();
         if(mensaplanDBHelper == null)
             mensaplanDBHelper = new MensaplanDatabaseHelper(AppContext, database);
         return mensaplanDBHelper.getWeeksWithPlanData(timeFrom, timeTo);
     }
 
     public void updateNewsItem(NewsItem news) {
+        openDatabase();
         if(newsDBHelper == null)
             newsDBHelper = new NewsDatabaseHelper(AppContext, database);
         newsDBHelper.updateNewsItem(news);
     }
 
     public NewsItem[] getNewsItems(String source, long timeFrom, long timeTo) {
+        openDatabase();
         if(newsDBHelper == null)
             newsDBHelper = new NewsDatabaseHelper(AppContext, database);
         return newsDBHelper.getNewsItems(source, timeFrom, timeTo);