package org.keyscience.Database;

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

public class DatabaseHelper extends SQLiteOpenHelper {
    // If the DB schema changes, change the DB.
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "users.db";

    private static final String SQL_CREATE_USER_TABLE =
            "CREATE TABLE " + EcoQuestDBContract.UserTable.TABLE_NAME + " (" +
                    EcoQuestDBContract.UserTable._ID + " INTEGER PRIMARY KEY," +
                    EcoQuestDBContract.UserTable.NAME + " TEXT," +
                    EcoQuestDBContract.UserTable.BIO + " TEXT," +
                    EcoQuestDBContract.UserTable.RANK + " INTEGER," +
                    EcoQuestDBContract.UserTable.TOTAL_COMPLETED_QUESTS + " INTEGER," +
                    EcoQuestDBContract.UserTable.POINTS + " INTEGER," +
                    EcoQuestDBContract.UserTable.EMAIL + " TEXT)";

    private static final String SQL_CREATE_COMPLETED_QUEST_TABLE =
            "CREATE TABLE " + EcoQuestDBContract.CompletedQuest.TABLE_NAME + " (" +
                    EcoQuestDBContract.CompletedQuest.QUEST_ID + " INTEGER," +
                    EcoQuestDBContract.CompletedQuest.USER_ID + " INTEGER," +
                    "FOREIGN KEY (" + EcoQuestDBContract.CompletedQuest.USER_ID + ") REFERENCES "
                    + EcoQuestDBContract.UserTable.TABLE_NAME + "(" + EcoQuestDBContract.UserTable._ID + "));";

    private static final String SQL_DELETE_COMPLETED_QUEST_TABLE =
            "DROP TABLE IF EXISTS " + EcoQuestDBContract.CompletedQuest.TABLE_NAME;
    private static final String SQL_DELETE_USER_TABLE =
            "DROP TABLE IF EXISTS " + EcoQuestDBContract.UserTable.TABLE_NAME;

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_USER_TABLE);
        db.execSQL(SQL_CREATE_COMPLETED_QUEST_TABLE);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        db.execSQL(SQL_DELETE_COMPLETED_QUEST_TABLE);
        db.execSQL(SQL_DELETE_USER_TABLE);
        onCreate(db);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }

}
