#include "mainForm.h"
#include <QApplication>
#include <QDir>
#include <QResource>
#include <QThread>
#include "QsLog.h"
#include "preDefine.h"
#include "dbsetForm.h"
#include "Control/flowControl.h"
#include "Control/refundControl.h"
#include "floatForm.h"
#include "DTools/configManger.h"
#include <windows.h>

using namespace QsLogging;

QString g_appDir;

QThread  workThread;
QThread refundThread;

void InitLogger()
{
    QString logDir = QString("%1/log").arg(g_appDir);
    Logger& logger = Logger::instance();
    logger.setLoggingLevel(TraceLevel);
    QDir().mkdir(logDir);
    QString logPath = QString("%1/%2").arg(logDir).arg("log");
    DestinationPtr fileDst(DestinationFactory::MakeFileDestination(
    logPath, EnableLogRotation, MaxSizeBytes(2*1024*1024), MaxOldLogCount(50)));
    logger.addDestination(fileDst);
    DestinationPtr consoleDst(DestinationFactory::MakeDebugOutputDestination());
    logger.addDestination(consoleDst);
}

void LoadTheme(const QString& theme)
{
    QString rccPath = QString("%1/skin/%2.rcc").arg(g_appDir).arg(theme);
    if(!QFile(rccPath).exists())
    {
        return;
    }
    QResource::registerResource(rccPath);

    QFile qssFile(QString(":/%1.qss").arg(theme));
    if(!qssFile.open(QFile::ReadOnly))
    {
        return;
    }
    qApp->setStyleSheet(qssFile.readAll());
    qssFile.close();
}

int main(int argc, char *argv[])
{
    HANDLE m_hMutex  =  CreateMutex(NULL, FALSE,  L"fmTakeaway" );

    if  (GetLastError()  ==  ERROR_ALREADY_EXISTS)  {
        CloseHandle(m_hMutex);
        m_hMutex  =  NULL;
        return  -1;
    }

    QApplication a(argc, argv);
    g_appDir = a.applicationDirPath();

    // 初始化日志
    InitLogger();

    // 加载主题
    LoadTheme(APP_THEME);

    QLOG_INFO() << QString("-------- fmTakeaway[%1] Start --------").arg(APP_VERSION);

    // 将控制器移到工作线程

    FlowControl::GetInstance().moveToThread(&workThread);
    workThread.start();

    FloatForm f;
    MainForm w;
    QObject::connect(&w, &MainForm::showFloatForm, &f, &FloatForm::onShow);
    QObject::connect(&w, &MainForm::startRemind, &f, &FloatForm::onStartRemind);
    QObject::connect(&w, &MainForm::stopRemind, &f, &FloatForm::onStopRemind);
    QObject::connect(&f, &FloatForm::showMainForm, &w, &MainForm::show);

    w.MyShow();

    return a.exec();
}
