//-*-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 "pinserver.h"
#include <kmessagebox.h>
#include <qtimer.h>
#include "pindialog.h"
#include <libkbluetooth/hcisocket.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <kdebug.h>

PinServer::PinServer(QObject *parent) :
    DCOPObject("PinServer"), QObject(parent)
{
    ownAuthenticationFlag = false;
    hciSocket = new KBluetooth::HciSocket(this);
    connect(hciSocket, SIGNAL(event(unsigned char, QByteArray)),
        this, SLOT(slotHciEvent(unsigned char, QByteArray)));
    hciSocket->open();
}

PinServer::~PinServer()
{
}

QString PinServer::pinDialog(bool incoming, QString addr, QString name)
{
    // "in" should be "out" and vice versa..
    return PinDialog::getPin((incoming == false), ownAuthenticationFlag, addr, name);
}

void PinServer::slotHciEvent(unsigned char event, QByteArray data)
{
    // TODO: also generate pin for incoming connections
    // when authentication is always enabled in hcid.conf
    if (event == EVT_CMD_STATUS) {
        QDataStream ds(data, IO_ReadOnly);
        uint8_t status; ds >> status;
        uint8_t numPackets; ds >> numPackets;
        uint16_t opcode; ds >> opcode;
        if (status == 0 && opcode == 0x1104 /* auth_req */) {
            kdDebug() << "PinServer PIN generation enabled" << endl;
            ownAuthenticationFlag = true;
            QTimer::singleShot(5000, this, SLOT(resetOwnAuthtenticationFlag()));
        } 
    }
}

void PinServer::resetOwnAuthtenticationFlag()
{
    ownAuthenticationFlag = false;
}

#include "pinserver.moc"
