#include "zeipisdesktopepg.h"
#include "mainwindow.h"
#include <qsqldatabase.h>
#include <qmessagebox.h>
#include <fstream>
#include <string>
#include <cctype>
#include <iostream>

ZeipisDesktopEPG::ZeipisDesktopEPG(int& argc, char** argv)
 : QApplication(argc, argv)
{
    readConfigAndOpenDB();
    myMainWindow = new MainWindow(0, *myCoreServerHostname, myCoreServerPort);
    setMainWidget(myMainWindow);
    myMainWindow->show();
    //QObject::connect(getmainWidget()), SIGNAL(fileExit()), this, SLOT(quit()));
}

ZeipisDesktopEPG::~ZeipisDesktopEPG()
{
}

std::string stringToLowerCase(std::string str)
{
  for (unsigned int i = 0; i < str.length(); i++)
    str[i] = std::tolower(str[i]);
  return str;
}

// Reads ini-style files into memory. Implementation from EPGKylix.
typedef std::map<std::string, std::string> Settings;
bool readConfigFile(const char* filename, Settings& settings)
{
  std::fstream file(filename, std::ios::in);
  if (!file.is_open())
    return false;

  std::string line, key, value;
  while (!file.eof())
  {
    std::getline(file, line);

    if(line[0] == '#' || line.empty())
      continue;

    int split = line.find('=');
    if (split == -1)
      continue;

    key = stringToLowerCase(line.substr(0, split));
    value = line.substr(split + 1, line.length() - split);

    settings[key] = value;
  }
  return true;
}

void ZeipisDesktopEPG::readConfigAndOpenDB()
{
  // Read file(s).
  // Settings in more user-close files overwrite system files - per setting
  Settings settings;
  readConfigFile("/etc/zeipis/start.conf", settings);
  std::string homefile = getenv("HOME");
  homefile += "/.zeipis/start.conf";
  readConfigFile(homefile.c_str(), settings);
  // check
  if (settings["dbhostname"].empty())
  {
    QMessageBox::critical(0, tr("Zeipis EPG - Database login missing"),
            tr("start.conf cound not be found and read. "
               "Please create a valid config file. "
               "See the Zeipis docs for more info."));
    exit(1);
  }

  // open database
  QString connector = "QMYSQL3";
  if (settings["dbtype"].compare("MySQL") == 0)
  	connector = "QMYSQL3";
  QSqlDatabase *zeipisConn = QSqlDatabase::addDatabase(connector, "zeipisConn");
  zeipisConn->setDatabaseName(settings["dbname"].c_str());
  zeipisConn->setUserName(settings["dbusername"].c_str());
  zeipisConn->setPassword(settings["dbpassword"].c_str());
  zeipisConn->setHostName(settings["dbhostname"].c_str());
  if (!zeipisConn->open())
  {
    printf("Database could not be accessed. Please check database.conf.\n");
    QMessageBox::critical(0, tr("Zeipis EPG - Database login failed"),
            tr("Database could not be accessed. "
               "Please check the configuration in database.conf."));
    exit(1);
  }

  myCoreServerHostname = new QString(settings["coreserverhostname"].c_str());
  if (settings.find("CoreServerPort") == settings.end()) // no port in config file
  	myCoreServerPort = 4962; // default port
  else
  	myCoreServerPort = QString(settings["coreserverport"].c_str()).toInt();
}

QString& ZeipisDesktopEPG::coreServerHostname()
{
  return *myCoreServerHostname;
}


int main(int argc, char **argv)
{
    ZeipisDesktopEPG app(argc, argv); // reads config, creates MainWindow and shows it
    return app.exec(); // main loop
}
