//-*-c++-*-
/***************************************************************************
 *   Copyright (C) 2003 by Fred Schaettgen                                 *
 *   kdebluetooth@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 <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "scosocket.h"
#include "deviceaddress.h"
#include <bluetooth/bluetooth.h>
#include <bluetooth/sco.h>
#include <kdebug.h>

namespace KBluetooth {

void ScoSocket::connectToHost(const DeviceAddress& addr)
{
    kdDebug() << QString("ScoSocket::connectToHost(%1)")
        .arg(QString(addr)) << endl;
    //TODO: connectToHost should return immediately.
    sockaddr_sco rem_addr, loc_addr;
    int s;

    if( (s = ::socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO)) < 0 ) {
        emit error(errno);
        kdDebug() << QString("Can't create socket. %1(%2)")
            .arg(strerror(errno)).arg(errno) << endl;
        return;
    }

    memset(&loc_addr, 0, sizeof(loc_addr));
    loc_addr.sco_family = AF_BLUETOOTH;
    loc_addr.sco_bdaddr = DeviceAddress::any.getBdaddr();
    if (bind(s, (struct sockaddr *) &loc_addr, sizeof(loc_addr)) < 0 ) {
        emit error(errno);
        kdDebug() << QString("Can't bind socket. %1(%2)")
            .arg(strerror(errno)).arg(errno) << endl;
        return;
    }

    memset(&rem_addr, 0, sizeof(rem_addr));
    rem_addr.sco_family = AF_BLUETOOTH;
    rem_addr.sco_bdaddr = addr.getBdaddr();
    if(::connect(s, (struct sockaddr *)&rem_addr, sizeof(rem_addr)) < 0 ){
            kdDebug() << QString("Can't connect. %1(%2)")
                .arg(strerror(errno)).arg(errno) << endl;
            ::close(s);
            return;
    }
    kdDebug() << "Connected." << endl;
    setSocket(s);
    //writeBlock("hello world", 12);
    //::write(s, "hello world", 12);
    emit connected();
}

ScoSocket::ScoSocket(QObject* parent, const char* name) :
    QSocket(parent, name)
{

}

ScoSocket::~ScoSocket()
{

}


}
#include "scosocket.moc"
