#include "beamupfilemonitor.h"
#include "qggrifobeamupproperties.h"

#include <windows.h>

#include <QStorageInfo>

#include "mydebug.h"

#include <windows.h>
#include <Dbt.h>


BeamupFileMonitor::BeamupFileMonitor(QObject *parent) : QObject(parent)
{
}

bool BeamupFileMonitor::nativeEventDriveDetection(const QByteArray &/*eventType*/, void *message, long */*result*/)
{
    if (!QgGrifoBeamupProperties::instance().m_watchRemovable)
        return false;

    MSG* msg = reinterpret_cast<MSG*>(message);
    if (msg->message == WM_DEVICECHANGE) {
        switch (msg->wParam) {
        case DBT_DEVICEARRIVAL:
            MyDebug.logMsg( type_log_info, origin_msg_generic ,"Device connected");
            enumDisks();
            return true;
            break;
        case DBT_DEVICEREMOVECOMPLETE:
            MyDebug.logMsg( type_log_info, origin_msg_generic ,"Device disconnected");
            enumDisks();
            return true;
            break;
        default:
            break;
        }
    }
    return false;

}

void BeamupFileMonitor::cleanUp()
{
}

#include <fileapi.h>

void BeamupFileMonitor::enumDisks()
{
    auto dlist=QDir::drives();
    QStringList tmp;

    QString deployPath=QgGrifoBeamupProperties::instance().m_watchRemovablePath;
    if (deployPath.isEmpty())
        deployPath="GRIFO-E-Deploy";

    foreach (auto d, dlist)
    {
        UINT t=GetDriveTypeA(d.filePath().toLatin1().constData());
        if (t==2)
        {
            if (removeableDisks.contains(d.filePath()))
                continue;
            else
            {
                MyDebug.logMsg( type_log_info,
                                  origin_msg_generic ,
                                  QString("new %1 %2").arg(d.filePath()).arg(t));
                tmp.append(d.filePath());
                QFileInfo f(d.filePath()+deployPath);
                if (f.isDir())
                {
                    QDir dir(f.absoluteFilePath());
                    auto L=dir.entryInfoList(QStringList()<<"*.zip", QDir::Files);
                    foreach(auto l, L)
                    {
                        MyDebug.logMsg( type_log_info,
                                          origin_msg_generic ,
                                          QString("Deployable %1").arg(l.absoluteFilePath()));
                    }
                }
            }
        }
    }
    removeableDisks=tmp;
}
