#include "Application.h"

#include <qdatetime.h>
#include <QtCore/QCoreApplication>
#include <QFrame>
#include <QVBoxLayout>
#include <QDialog>

#include "../utils/MessageException.h"
#include "../widgets/TitleBar.h"
#include "../widgets/DialogTemplate.h"

Application *Application::m_instance = NULL;

/**
 * @brief Application::instance 单例模式，方便调用
 * @return Application实例
 */
Application *Application::instance()
{
    static QMutex mutex;
    if (!m_instance)
    {
        QMutexLocker locker(&mutex);
        if (!m_instance)
        {
            m_instance = new Application;
        }
    }

    return m_instance;
}

Application::Application():
    inited(false),
    configurator(0),
    dbConnector(0)
{

}


Application::~Application()
{
    if(m_instance != NULL)
    {
        m_instance->uninit();

        delete  m_instance;
        m_instance = NULL;
    }
}

void Application::init()
{
    if(inited)
        return;

    try 
    {
        // 初始化系统配置模块
        configurator = new ApplicationConfigurator();
        configurator->init();

        sendMessage("加载配置文件成功", false);

        // 初始化数据库连接模块
        dbConnector = new DatabaseConnector();
		dbConnector->init(configurator->getDbName(),
                          configurator->getDbHostName(),
						  configurator->getDbPort(),
                          configurator->getDbUserName(),
                          configurator->getDbPassword());
        sendMessage("系统启动成功!", false);

        inited = true;
    }
    catch (MessageException& e)
    { 
        sendMessage(e.getMessage(), true);
    }
}

void Application::uninit()
{
    if (dbConnector)
    {
        delete dbConnector;
    }
    if (configurator)
    {
        delete configurator;
    }
}

void Application::showLoading(const QString &msg)
{
	emit loading(true, msg);
}

void Application::hideLoading()
{
	emit loading(false);
}

int Application::showModalDialog(QWidget *contentWidget, QWidget *parent)
{
	DialogTemplate *dt = new DialogTemplate(contentWidget, parent);
	contentWidget->setParent((QWidget*)dt);
	dt->setWindowTitle(contentWidget->windowTitle());
	dt->setWindowIcon(QIcon(":/MainWindow/Resources/App.ico"));
	return dt->exec();
}

void Application::sendMessage(const QString &msg, bool err)
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QString showMsg = "时间:" + currentTime.toString("yyyy-MM-dd hh:mm:ss");
    showMsg.append("\t" + msg);
    emit message(showMsg, err);
}

