#include "omobidisplaybackend.h"

OmobiDisplayBackend::OmobiDisplayBackend(QObject *parent) : QObject(parent)
{

    this->ble = new QBluetoothLeUart();

    connect(this->ble, &QBluetoothLeUart::stateChanged, this, &OmobiDisplayBackend::handleBluetoothStateChange);
    connect(this->ble, &QBluetoothLeUart::foundNewDevice, this, &OmobiDisplayBackend::handleFoundNewDevice);
    connect(this->ble, &QBluetoothLeUart::dataReceived, this, &OmobiDisplayBackend::DataHandler);

}


void OmobiDisplayBackend::startScanning() {
    this->ble->startScanningForDevices();
}

void OmobiDisplayBackend::handleBluetoothStateChange(QBluetoothLeUart::BluetoothLeUartState state){

    qDebug() << state;

    switch(state){

        case QBluetoothLeUart::Scanning:
        {
            qDebug() << "Now scanning";
            break;
        }


        case QBluetoothLeUart::ScanFinished:
        {
            qDebug() << "Scan finished";

            break;
        }

        case QBluetoothLeUart::Connecting:
        {
            qDebug() << "Now connecting";
            break;
        }
        case QBluetoothLeUart::Connected:
        {
            qDebug() << "Connected.";
            break;
        }
        case QBluetoothLeUart::ServiceFound:
        {
            qDebug() << "Service found!";
            break;
        }
        case QBluetoothLeUart::AcquireData:
        {
            qDebug() << "Now acquiring data!";

            /* Initialise Slot DataHandler(QString) - gets new data */

            this->ble->sendData("Hat geklappt");
            break;
        }
        default:
            //nothing for now
        break;


    }
}

void OmobiDisplayBackend::handleFoundNewDevice(BluetoothDeviceInfo* device) {
    qDebug() << "Found a device: name: " << device->getName() << " address: " << device->getAddress();

    if(device->getName() == "ESP32 Chat Test") {
        this->ble->stopScanningForDevices();
        this->ble->connectToDevice(device);
    }
}

void OmobiDisplayBackend::DataHandler(const QString &s){

    qDebug() << "NEw data: " << s;

}

