/* Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved.

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; version 2 of the License.

There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-C++ in the directory of this
software distribution.

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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

/* Standard C++ includes */
#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <crypt.h>
#include <climits>
#include <unistd.h>
#include <sys/stat.h>

#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/metadata.h>
#include <cppconn/parameter_metadata.h>
#include "sql.hh"
#include "common.hh"
#include "config.hh"

#define BCRYPT_HASHSIZE	(64)
#define RANDBYTES (16)
#define COST (12)
#ifndef DROP
#define DROP false
#endif


using namespace std;

int hathor_install_schema( sql::Connection* connection ) {

  json j = parse_file("config.json");
  scanner_config s_opts = hathor_config(j);

  char databaseSql[50] = "CREATE DATABASE IF NOT EXISTS ";
  strcat(databaseSql, s_opts.mysql.db.c_str());
  if(strcmp(s_opts.php.pass.c_str(), "null") == 0)
  {
    s_opts.php.pass = getPass("Enter new password for admin user : ", '*');
  }
  try
  {

    sql::Statement *statement = connection->createStatement();
    statement->execute(databaseSql);
    connection->setSchema(s_opts.mysql.db);
    sql::PreparedStatement *pstmt;

    if(DROP)
    {
      statement->execute(SqlMap["playlistsSql"]);
      statement->execute(SqlMap["tracksSql"]);
      statement->execute(SqlMap["albumsSql"]);
      statement->execute(SqlMap["artistsSql"]);
      statement->execute(SqlMap["userSql"]);
    }
    statement->execute(SqlMap["userCreateSql"]);
    statement->execute(SqlMap["artistCreateSql"]);
    statement->execute(SqlMap["albumCreateSql"]);
    statement->execute(SqlMap["tracksCreateSql"]);
    statement->execute(SqlMap["playlistsCreateSql"]);
    pstmt = connection->prepareStatement("INSERT IGNORE INTO users(uid,username,email,password,isadmin) VALUES (?,?,?,?,?)");
    pstmt->setString(1, s_opts.php.user.c_str());
    pstmt->setString(2, s_opts.php.user);
    pstmt->setString(3, s_opts.php.email);
    pstmt->setString(4, s_opts.php.pass.c_str());
    pstmt->setInt(5, 1);
    pstmt->executeQuery();
    connection->commit();
    delete pstmt;
    delete statement;
  }
  catch (sql::SQLException &e)
  {
    cout << "# ERR: SQLException in " << __FILE__;
    cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
    cout << "# ERR: " << e.what();
    cout << " (MySQL error code: " << e.getErrorCode();
    cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    return 0;
  }
  catch(std::exception &e)
  {
    cout << e.what() << endl;
    return 0;
  }
  cout << "Installed database tables into " << s_opts.mysql.db << "." << endl;
  return 0;
}

sql::Connection* get_connection(
  const char * user,
  const char * password,
  const char * host = "localhost",
  unsigned short port=3306
  )
{
  sql::Driver *driver = sql::mysql::get_driver_instance();
  driver->threadInit();
  char connection[255];
  sprintf(connection, "tcp://%s:%d", host, port);
  sql::Connection *con = driver->connect(connection, user, password);
  driver->threadEnd();
  return con;
}
unsigned int get_max_statements( sql::Connection *connection )
{
  std::string::size_type size;
  unsigned int maxPstms = stoi(dynamic_cast< sql::mysql::MySQL_Connection * >(
    connection->getMetaData()->getConnection()
    )->getSessionVariable("max_prepared_stmt_count"), &size);

    return ( maxPstms == 0 ) ? 10000 : maxPstms;

}
#ifdef TEST
int main(int argc, char * argv[])
{

//sql::PreparedStatement *artist, *album, *track, *user;

if(argc == 2) {
  char * cmd = argv[1];
  for(unsigned int i=0; i<strlen(cmd); i++ ) {
    cmd[i] = tolower(cmd[i]);
  }
  if( strcmp(cmd, "--drop-tables") == 0 ) {
    // hathor_install_schema(con,true);
  } else {
    cout << endl << "Usage : scanner [--install-schema]\n\n" <<
    "--drop-tables\tDrops the database tables\n" <<
    "                \tbefore trying to create them.\n";
    return EXIT_SUCCESS;
  }
}

json j = parse_file("config.json");
scanner_config s_opts = hathor_config(j);

cout << endl;
if(strcmp(s_opts.mysql.pass.c_str(), "null") == 0)
{
  cout << "MySQL password not found in config.json.\n" << endl;
  s_opts.mysql.pass = getPass("Enter MySQL password. : ", '*');
}
cout << endl;


try {

  /* Connect to the MySQL test database */
  sql::Connection *con = get_connection(
    s_opts.mysql.user.c_str(),
    s_opts.mysql.pass.c_str(),
    s_opts.mysql.host.c_str(),
    s_opts.mysql.port
   );

  try {
    hathor_install_schema(con);
  } catch(std::exception &e) {
    cout << e.what() << endl;
  }

  //con->setAutoCommit(0);


  //sql::PreparedStatement *pstmt = con->prepareStatement("INSERT IGNORE INTO users(username,email,password,isadmin) VALUES (?,?,?,?)");

  /*for(unsigned int i = 1; i<=10; i++ )
  {
      cout << "Queueing record " << i << "." << endl;
      pstmt->setString(1, "eric");
      pstmt->setString(2, "eric@rewiv.com");
      pstmt->setString(3, "password");
      pstmt->setInt(4,false);
      pstmt->executeUpdate();

      pstmt2->setString(1, "eric1");
      pstmt2->setString(2, "eric1@rewiv.com");
      pstmt2->setString(3, "password");
      pstmt2->setInt(4,true);
      pstmt2->executeUpdate();

    if( ( i % maxPreparedStatements ) == 0 || ( i % maxPreparedStatements ) == maxPreparedStatements ) {
      cout << "Commiting " << i << " records." << endl;
      con->commit();
      pstmt->clearParameters();
      pstmt2->clearParameters();
    }
  }

  cout << "Commiting last updates ..." << endl;
  con->commit();
*/

   //delete pstmt;
   //delete pstmt2;
   delete con;
   //delete artist, album, track, user;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
  return 0;
} catch(std::exception &e){
  cout << e.what() << endl;
}

cout << endl;

return EXIT_SUCCESS;
}
#endif
