#ifndef ACCELEROMETERFILTER_H
#define ACCELEROMETERFILTER_H

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

QTM_USE_NAMESPACE

#define RADIANS_TO_DEGREES 57.2957795

class AccelerometerFilter : public QObject, public QAccelerometerFilter
{
    Q_OBJECT
protected:
    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);

        // Lowpass factor
#ifdef Q_OS_SYMBIAN
        float lowPassFactor = 0.10;
#else
        float lowPassFactor = 0.05;
#endif

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

#if defined(Q_OS_SYMBIAN)
        emit rotationChanged(-y);
#else
        emit rotationChanged(x);
#endif

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

signals:
    void rotationChanged(QVariant deg);
};

#endif // ACCELEROMETERFILTER_H
