/*
 * SmartHome server: Plug-in timer
 *
 * Copyright (C) 2010 Daniel Pisi <dan.pisi@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of version 2 of the GNU General Public License
 * as published by the Free Software Foundation.
 *
 */

/**
 * @file shtimer.cpp
 * @brief Implements a simple timer
 * @author Daniel Pisi
 */

#include "shtimer.h"

// -----------------------------------------------------------------------------

/**
 * \brief Constructor of ShTimer
 */
ShTimer::ShTimer()
{
    mOutput = false;

    mTimer = new QTimer(this);
    mTimer->setSingleShot(true);

    connect(mTimer, SIGNAL(timeout()), this, SLOT(onTimeout()));
}
// -----------------------------------------------------------------------------

/**
 * \brief Initialization of the plug-in
 * \param param Defines a timer period
 * \return true if the plug-in has been initialized successfully
 */
bool ShTimer::init(QString param)
{
    bool ok = false;
    double sec;

    sec = param.toDouble(&ok);
    mTimer->setInterval(ok ? sec*1000 : 1000);

    qDebug("Timer initialized");
    return true;
}
// -----------------------------------------------------------------------------

void ShTimer::onTimeout()
{
    mOutput = false;
    outputUpdated("Y", mOutput);
}
// -----------------------------------------------------------------------------

/**
 * \brief Processes incomming messages (input changes)
 * \param message Shared pointer to the message
 */
void ShTimer::processMessage(ShMessagePtr message)
{
    qDebug("Timer: Processing message from object %d, signal = %s, value = %s",
           message->senderId(), qPrintable(message->signal()), qPrintable(message->value().toString()));

    if (message->msgType() == ShMessage::mtValue)
    {
        if ((message->signal() == "X") &&
            (message->value().toBool() != mOutput))
        {
            mOutput = message->value().toBool();

            if (mOutput)
            {
                outputUpdated("Y", true);
                mTimer->start();
            }
            else
            {
                mTimer->stop();
                outputUpdated("Y", false);
            }
        }

        if (message->requireAck())
            ackMessage(message);
    }
    else if ((message->msgType() == ShMessage::mtGet) &&
             (message->signal() == "Y"))
    {
        outputUpdated("Y", mOutput);
    }
}
// -----------------------------------------------------------------------------

Q_EXPORT_PLUGIN2(timer, ShTimer);
