/*!
  \file
  \brief 送受信データを記録する Connection クラス

  \author Satofumi KAMIMURA

  $Id: RecordConnection.cpp 1839 2010-06-05 05:40:50Z satofumi $
*/

#include "RecordConnection.h"
#include "Connection.h"
#include <fstream>
#include <string>

using namespace qrk;
using namespace std;


struct RecordConnection::pImpl
{
    string error_message_;
    Connection* connection_;
    ofstream send_fout_;
    ofstream receive_fout_;


    pImpl(Connection* connection,
          const char* send_save_file, const char* receive_save_file)
        : error_message_("no error."), connection_(connection)
    {
        send_fout_.open(send_save_file);
        receive_fout_.open(receive_save_file);
    }
};


RecordConnection::RecordConnection(Connection* connection,
                                   const char* send_save_file,
                                   const char* receive_save_file)
    : pimpl(new pImpl(connection, send_save_file, receive_save_file))
{
}


RecordConnection::~RecordConnection(void)
{
}


const char* RecordConnection::what(void) const
{
    return pimpl->error_message_.c_str();
}


bool RecordConnection::connect(const char* device, long baudrate)
{
    return pimpl->connection_->connect(device, baudrate);
}


void RecordConnection::disconnect(void)
{
    pimpl->connection_->disconnect();
}


bool RecordConnection::setBaudrate(long baudrate)
{
    return pimpl->connection_->setBaudrate(baudrate);
}


long RecordConnection::baudrate(void) const
{
    return pimpl->connection_->baudrate();
}


bool RecordConnection::isConnected(void) const
{
    return pimpl->connection_->isConnected();
}


int RecordConnection::send(const char* data, size_t count)
{
    int n = pimpl->connection_->send(data, count);
    if (n > 0) {
        pimpl->send_fout_.write(data, n);
    }
    return n;
}


int RecordConnection::receive(char* data, size_t count, int timeout)
{
    int n = pimpl->connection_->receive(data, count, timeout);
    if (n > 0) {
        pimpl->receive_fout_.write(data, n);
    }
    return n;
}


size_t RecordConnection::size(void) const
{
    return pimpl->connection_->size();
}


void RecordConnection::flush(void)
{
    pimpl->connection_->flush();
}


void RecordConnection::clear(void)
{
    pimpl->connection_->clear();
}


void RecordConnection::ungetc(const char ch)
{
    pimpl->connection_->ungetc(ch);
}
