#ifndef _USBThread_h__
#define _USBThread_h__

#include <QHash>
#include <QMutex>
#include <atomic>
#include <stdint.h>

#include "DaemonThread.h"
#include "source.h"

#include <dracal/common/chrono.hpp>

class TUSBProvider;

class USBThread : public DaemonThread {

    friend class TUSBProvider;

    Q_OBJECT

    USBThread();

  public:
    // Singleton instance
    static USBThread &instance() {
        static USBThread s_instance;
        return s_instance;
    }

    // Disable copy constructor and assignment operator
    // Required to enforce singleton pattern
    USBThread(USBThread const &) = delete;
    void operator=(USBThread const &) = delete;

    virtual ~USBThread();

    virtual void run();
    virtual void shutdown();

    void setPollInterval(const unsigned int ms);
    void setVirtualOptions(const unsigned int flags, const double slp);
    void setUserCalibration(const QString &serialNumber, const int channelIndex, const bool on);

  private:
    void poll(const int64_t timestamp);

    enum State { INIT, SHUTDOWN };

    QMutex _mutex;
    std::atomic<State> _state{INIT};

    int64_t _start_timestamp;
    std::atomic<chrono::milliseconds> _interval{chrono::milliseconds{1000}};

    QHash<QString, Source *> _sourcesBySerialNumber;
};

#endif
