#include "launcher.h"

#include <QApplication>
#include "logproc.h"
#include <windows.h>
#include <DbgHelp.h>
#include "CLogTrack.h"

long  __stdcall CrashInfocallback(_EXCEPTION_POINTERS *pexcp)
{
    //创建 Dump 文件
    HANDLE hDumpFile = ::CreateFile(
                L"launcher.dmp",
                GENERIC_WRITE,
                0,
                NULL,
                CREATE_ALWAYS,
                FILE_ATTRIBUTE_NORMAL,
                NULL
                );
    if (hDumpFile != INVALID_HANDLE_VALUE)
    {
        //Dump信息
        MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
        dumpInfo.ExceptionPointers = pexcp;
        dumpInfo.ThreadId = GetCurrentThreadId();
        dumpInfo.ClientPointers = TRUE;
        //写入Dump文件内容
        ::MiniDumpWriteDump(
                    GetCurrentProcess(),
                    GetCurrentProcessId(),
                    hDumpFile,
                    MiniDumpNormal,
                    &dumpInfo,
                    NULL,
                    NULL
                    );
    }

    EXCEPTION_RECORD* record = pexcp->ExceptionRecord;
    QString errCode(QString::number(record->ExceptionCode,16)),
            errAdr(QString::number((uint)record->ExceptionAddress,16));

    HWND task = nullptr;
    task=FindWindow(L"Shell_TrayWnd",nullptr);
    if(task)
    {
        ShowWindow(task,SW_SHOW);//隐藏任务栏
    }

    QMessageBox::critical(NULL,QString::fromLocal8Bit("程序崩溃"),
                          QString::fromLocal8Bit("<FONT size=4><div><b>对于发生的错误，表示诚挚的歉意</b><br/></div>")+
        QString::fromLocal8Bit("<div>错误代码：%1</div><div>错误地址：%2</div></FONT>").arg(errCode).arg(errAdr),
        QMessageBox::Ok);
    myDebug()<<QString::fromLocal8Bit("程序崩溃,错误代码：%1,错误地址：%2").arg(errCode).arg(errAdr);

    return 0;
}


int main(int argc, char *argv[])
{               
   // g_logPtr = std::make_shared<CLogTrack>("examcloud", "cn-shenzhen.log.aliyuncs.com", "student_2_client");

    QApplication a(argc, argv);
    launcher w;
    w.show();

    qInstallMessageHandler(CustomOutputMessage);
    ::SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)CrashInfocallback);

    return a.exec();
}
