#ifndef ACCELEROMETERFILTER_H
#define ACCELEROMETERFILTER_H

#include <QAccelerometerFilter>
#include <math.h>
#include <QVariant>

QTM_USE_NAMESPACE

#define RADIANS_TO_DEGREES 57.2957795

class Signaler : public QObject
{
    Q_OBJECT

public:
    void emitSignal(qreal x, qreal y, qreal z)
    {
        emit rotationChanged(x, y, z);
    }

signals:
    void rotationChanged(QVariant x, QVariant y, QVariant z);
};


class AccelerometerFilter : public QAccelerometerFilter
{
protected:
    Signaler m_Signaler;

    qreal x;
    qreal y;
    qreal z;

public:
    AccelerometerFilter() : x(0), y(0), z(0) {}

    bool filter(QAccelerometerReading *reading)
    {
        qreal rx = reading->x();
        qreal ry = reading->y();
        qreal rz = reading->z();

        qreal divider = sqrt(rx*rx + ry*ry + rz*rz);

        // Calculate the axis angles in degrees and reduce the noise in sensor readings
        x += (acos(rx / divider) * RADIANS_TO_DEGREES - 90 - x) * 0.05;
        y += (acos(ry / divider) * RADIANS_TO_DEGREES - 90 - y) * 0.05;
        z += (acos(rz / divider) * RADIANS_TO_DEGREES - 90 - z) * 0.05;

        m_Signaler.emitSignal(x, y, z);

        return false; // don't store the reading in the sensor
    }

    Signaler* getSignaler() { return &m_Signaler; }
};

#endif // ACCELEROMETERFILTER_H
