/*
 * Copyright (c) 2010 Nokia Corporation.
 */

#include <QApplication>
#include <QGraphicsObject>
#include <QDeclarativeView>
#include <QAccelerometer>
#include <QPointer>
#include <QDesktopWidget>
#include "accelerometerfilter.h"
#include "taskswitcher.h"
#include "settings.h"

// Lock orientation in Symbian
#ifdef Q_OS_SYMBIAN
    #include <eikenv.h>
    #include <eikappui.h>
    #include <aknenv.h>
    #include <aknappui.h>
#endif

QTM_USE_NAMESPACE

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

#ifdef Q_OS_SYMBIAN
    // Lock orientation in Symbian
    CAknAppUi* appUi = dynamic_cast<CAknAppUi*> (CEikonEnv::Static()->AppUi());
    TRAP_IGNORE( if(appUi) appUi->SetOrientationL(CAknAppUi::EAppUiOrientationLandscape); );
#endif

    QAccelerometer sensor;
    QPointer<AccelerometerFilter> filter = new AccelerometerFilter;
    sensor.addFilter(filter);   // does not take the ownership of the filter

    QDeclarativeView view;
    view.setSource(QUrl("qrc:/qml/bubblelevel.qml"));
    view.setResizeMode(QDeclarativeView::SizeRootObjectToView);

    QObject *rootObject = dynamic_cast<QObject*>(view.rootObject());

    TaskSwitcher taskSwitcher;
    Settings settings;

    // Associate Qt / QML signals and slots
    QObject::connect(rootObject, SIGNAL(minimizeApplication()), &taskSwitcher, SLOT(minimizeApplication()));
    QObject::connect(rootObject, SIGNAL(saveCorrectionAngle(QVariant)), &settings, SLOT(saveCorrectionAngle(QVariant)));
    QObject::connect(filter, SIGNAL(rotationChanged(QVariant)), rootObject, SLOT(handleRotation(QVariant)));
    QObject::connect(&settings, SIGNAL(correctionAngle(QVariant)), rootObject, SLOT(setCorrectionAngle(QVariant)));
    QObject::connect((QObject*)view.engine(), SIGNAL(quit()), &app, SLOT(quit()));

#ifdef Q_OS_SYMBIAN
    // Hide task switcher button in Symbian devices
    rootObject->setProperty("taskSwitcherVisible", false);
#endif

    // Read correction factor from permanent storage and emit it to QML side
    settings.loadAndEmitCorrectionAngle();

    // Begin measuring of accelerometer sensor
    sensor.start();

#if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN) || defined(Q_WS_SIMULATOR)
    view.setGeometry(QApplication::desktop()->screenGeometry());
    view.showFullScreen();
#else
    view.setGeometry((QRect(100, 100, 800, 480)));
    view.show();
#endif

    return app.exec();
}
