/*
 *
 *  Authorization Agent implementation of bluez5
 *
 *  Copyright (C) 2018  Emanoil Kotsev <deloptes@gmail.com>
 *
 *
 *  This file is part of tdebluezauth.
 *
 *  tdebluezauth is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  tdebluezauth is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with kbluetooth; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
#include <tqdbusobjectpath.h>
#include <tdecmdlineargs.h>
#include <tdemessagebox.h>

#include <adapterImpl.h>
#include "application.h"
#include "authservice.h"

#define DBUS_AUTH_SERVICE "TDEBluezAuth"
#define DBUS_AUTH_SERVICE_NAME  "org.trinitydesktop.tdebluez"

TDEBluezAuth::TDEBluezAuth() :
        KUniqueApplication()
{
    m_connection = TQT_DBusConnection::addConnection(TQT_DBusConnection::SystemBus, DBUS_AUTH_SERVICE);

    if (!m_connection.isConnected())
    {
        kdError() << "Failed to open connection to system message bus: " << m_connection.lastError().message() << endl;
        exit(-1);
    }

    // try to get a specific service name
    if (!m_connection.requestName(DBUS_AUTH_SERVICE_NAME))
    {
        tqWarning(i18n("Requesting name %1 failed. "
                "The object will only be addressable through unique name '%2'").arg(
                DBUS_AUTH_SERVICE_NAME).arg(m_connection.uniqueName()));
        exit(-2);
    }

    manager = new TDEBluetooth::ObjectManagerImpl("org.bluez", "/", this, "ObjectManager");
    if (!manager->isConnectedToDBUS())
    {
        tqDebug("ObjectManager is not connected to DBus");
        exit(-3);
    }

    rootService = new RootNodeService(m_connection);
    orgService = new OrgNodeService(m_connection);
    tdeNodeService = new TrinityDekstopNodeService(m_connection);
    authService = new AuthService(m_connection);
    agentManager = 0;
    if (!configureAgent())
    {
        tqDebug("Failed to configure the auth agent");
    }
    disableSessionManagement();

// connect to manager signals
//    connect(manager, SIGNAL(adapterAdded(const TQString&)), SLOT(slotAdapterAdded(const TQString&)));
//    connect(manager, SIGNAL(adapterRemoved(const TQString&)), SLOT(slotAdapterRemoved(const TQString&)));
    connect(manager, SIGNAL(adapterPowerOnChanged(const TQString&, bool)),
            this, SLOT(slotPowerOnChanged(const TQString&, bool)));
}

TDEBluezAuth::~TDEBluezAuth()
{
    disconnect(manager, SIGNAL(adapterPowerOnChanged(const TQString&, bool)),
            this, SLOT(slotPowerOnChanged(const TQString&, bool)));
    // close D-Bus connection
    unconfigureAgent();

    m_connection.closeConnection(DBUS_AUTH_SERVICE);

    delete authService;
    delete tdeNodeService;
    delete orgService;
    delete rootService;

    delete manager;
    agentManager = 0;
}

bool TDEBluezAuth::isConnectedToDBUS()
{
    return m_connection.isConnected();
}

bool TDEBluezAuth::configureAgent()
{
    if (!agentManager)
        agentManager = manager->getAgentManager();

    if (manager->isAgentRegistered() && manager->isAgentDefaultAgent())
    {
        return true;
    }

    if (!manager->isAgentRegistered())
    {
        if (!manager->registerAgent())
        {
            tqWarning("org.bluez.Agent1 registering FAILED");
            return false;
        }
    }
    if (!manager->isAgentDefaultAgent())
    {
        if (!manager->requestDefaultAgent())
        {
            tqWarning(i18n("org.bluez.Agent1 registering FAILED"));
            return false;
        }
    }

    kdDebug() << "org.bluez.Agent1 registering OK" << endl;

    return true;
}

bool TDEBluezAuth::unconfigureAgent()
{
    if (manager->isAgentRegistered())
    {
        if (manager->unregisterAgent())
            kdDebug() << "Agent unregistered OK" << endl;
        else
            kdDebug() << "Agent unregistered FAILED" << endl;
    }
    return true;
}

void TDEBluezAuth::slotPowerOnChanged(const TQString& adapter, bool state)
{
    if (state)
        configureAgent();
    else
        unconfigureAgent();
}

#include "application.moc"
