//-*-c++-*-
/***************************************************************************
 *   Copyright (C) 2003 by Fred Schaettgen                                 *
 *   kbluetoothd@schaettgen.de                                             *
 *                                                                         *
 *   This program 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.                                   *
 ***************************************************************************/

#include "hcidevmonitor.h"
#include <libkbluetooth/hcisocket.h>
#include <qtimer.h>
#include <kdebug.h>
#include <klocale.h>
#include <knotifyclient.h>
#include <kapplication.h>
#include <qwidget.h>

using namespace KBluetooth;

HciDevMonitor::HciDevMonitor(QObject *parent) :
    QObject(parent)
{
    hciSocket = new HciSocket();
    connect(hciSocket, SIGNAL(error(int,QString)), this, SLOT(slotHciSocketClosed()));
    //connect(hciSocket, SIGNAL(connectionClosed()), this, SLOT(slotHciSocketClosed()));
}

HciDevMonitor::~HciDevMonitor()
{
}

void HciDevMonitor::start()
{
    slotTimeout();
}

void HciDevMonitor::slotTimeout()
{
    ignoreSocketError = true;
    if (hciSocket->open()) {
        kdDebug() << "HciDevMonitor::slotTimeout(): Device found" << endl;
        emit hciDeviceFound();
        int winid = 0;
        if (KApplication::kApplication()->mainWidget()) {
            winid = KApplication::kApplication()->mainWidget()->winId();
        }
        KNotifyClient::event(winid, "BluetoothDeviceFound",
            i18n("Bluetooth adaptor found."));
    }
    else {
        if(!alertedNoStartupDevice) {
            emit hciNoStartupDevice();
            alertedNoStartupDevice = true;
        }
        QTimer::singleShot(5000, this, SLOT(slotTimeout()));
    }
    ignoreSocketError = false;
}

void HciDevMonitor::slotHciSocketClosed()
{
    if (ignoreSocketError == true) return;
    kdDebug() << "HciDevMonitor::slotHciSocketClosed(): Device lost" << endl;
    int winid = 0;
    if (KApplication::kApplication()->mainWidget()) {
        winid = KApplication::kApplication()->mainWidget()->winId();
    }
    KNotifyClient::event(winid, "BluetoothDeviceLost",
        i18n("Bluetooth adaptor was unplugged."));
    emit hciDeviceLost();
    QTimer::singleShot(1000, this, SLOT(slotTimeout()));
}

#include "hcidevmonitor.moc"
