#ifndef RcdWriterSkt_HH
#define RcdWriterSkt_HH

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>

#include "RcdWriter.hh"
#include "DuplexSocket.hh"

class RcdWriterSkt : public RcdWriter {

public:
  RcdWriterSkt() {
  }

  virtual ~RcdWriterSkt() {
    close();
  }

  bool open(std::string file) {
    _socket=new DuplexSocket(1124);
    //_socket=new DuplexSocket("localhost",1124,100);
    _numberOfBytes=0;

    if(_socket==0) {
      std::cerr << "RcdWriterSkt::open()   Error opening socket "
		<< _fileName << std::endl;
      return false;
    }

    std::cout << "RcdWriterSkt::open()   Opened socket "
	      << _fileName << std::endl;
    return true;
  }

  bool write(const RcdRecord &r) {
    if(_socket==0) return false;

    int n(r.totalNumberOfBytes());
    if(!_socket->send((const char*)(&r),n)) {
      std::cerr << "RcdWriterSkt::write()  Error writing to file; number of bytes written < "
	   << n << std::endl;
      perror(0);
      //_numberOfBytes+=n;
      return false;
    }

    _numberOfBytes+=r.totalNumberOfBytes();

    return true;
  }

  bool close() {
    if(_socket==0) return false;

    delete _socket;
    std::cout << "RcdWriterSkt::close()  Closed socket "
	      << _fileName << " after writing " << _numberOfBytes
	      << " bytes" << std::endl;

    _socket=0;
    _numberOfBytes=0;
    return true;
  }

  unsigned numberOfBytes() const {
    return _numberOfBytes;
  }


private:
  DuplexSocket *_socket;
  std::string _fileName;
  unsigned _numberOfBytes;
};

#endif
