#include <kore/kore.h>
#include <sqlite3.h>
#include <stdio.h>

int init_db(const char *name);
int check_db(const char *name);

int init_db(const char *name)
{
    sqlite3 *db = NULL;
    char *zErrMsg = 0;
    char *sql = "CREATE TABLE Users(" \
        "Email CHAR(70) PRIMARY KEY NOT NULL, " \
        "Password TEXT NOT NULL," \
        "Email_rescue TEXT," \
        "Alias TEXT," \
        "XMPP TEXT, " \
        "Active CHAR(3) NOT NULL, "             \
        "Token CHAR(30), " \
        "Website TEXT, " \
        "Date_create BIGINT );";

    int rc = sqlite3_open(name, &db);

    if (rc != SQLITE_OK) {
        kore_log(LOG_ERR, "Cannot create database: %s\n",
                 sqlite3_errmsg(db));
        sqlite3_close(db);
        return (KORE_RESULT_ERROR);
    }

    rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);

    if( rc != SQLITE_OK ){
        kore_log(LOG_ERR, "SQL error: %s", zErrMsg);
        sqlite3_free(zErrMsg);
    } else {
        kore_log(LOG_NOTICE, "Database successfully created !");
    }

    sqlite3_close(db);

    return 0;
}


int check_db(const char *name){
   sqlite3 *db = NULL;
   char *zErrMsg = 0;
   char *sql;
   int rc = sqlite3_open(name, &db);
   if (rc != SQLITE_OK) {
       kore_log(LOG_ERR, "Cannot open database: %s\n",
                sqlite3_errmsg(db));
       sqlite3_close(db);
       return (KORE_RESULT_ERROR);
   }

   sql = "SELECT EXISTS(SELECT 1 FROM Users WHERE Email=''); " \
       "SELECT EXISTS(SELECT 1 FROM Users WHERE Password='');" \
       "SELECT EXISTS(SELECT 1 FROM Users WHERE Email_rescue='');" \
       "SELECT EXISTS(SELECT 1 FROM Users WHERE Alias='');" \
       "SELECT EXISTS(SELECT 1 FROM Users WHERE XMPP='');" \
       "SELECT EXISTS(SELECT 1 FROM Users WHERE Active='');" \
       "SELECT EXISTS(SELECT 1 FROM Users WHERE Token='');" \
       "SELECT EXISTS(SELECT 1 FROM Users WHERE Website='');" \
       "SELECT EXISTS(SELECT 1 FROM Users WHERE Date_create='');";

   rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);

   if( rc != SQLITE_OK ){
        kore_log(LOG_ERR, "SQL error: %s", zErrMsg);
        sqlite3_free(zErrMsg);
        return 1;
   }
   else
   {
        kore_log(LOG_NOTICE, "Check database is 0K!");
    }

    sqlite3_close(db);


   return 0;
}
