#include "yyysound_client_noexception.H"

#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream.h>

yyysound_client_noexception::yyysound_client_noexception()
  : inited (0)
{
};

yyysound_client_noexception::~yyysound_client_noexception()
{
  if (inited) close(dsc);
};

int yyysound_client_noexception::init(const string &ip)
{
  cout <<"Trying connect to yyys (erikyyys soundserver) ...\n"
       <<"If it hangs here, you must:\n"
       <<"a) fetch and install the yyys package\n"
       <<"b) start the yyys server\n"
       <<"or disable sound in setupts/setup_client.set\n";
  struct in_addr adr;
  if (!inet_aton(ip.c_str(),&adr)) return 0;
  if ((dsc = ::socket(AF_INET,SOCK_STREAM,0))<0) return 0;
  int reuser=1;
  if (::setsockopt(dsc,SOL_SOCKET,SO_REUSEADDR,(void *)&reuser,sizeof(reuser))<0) { close(dsc); return 0; };
  sockaddr_in outgoing;
  memset(&outgoing,0,sizeof(outgoing));
  outgoing.sin_addr=adr;
  outgoing.sin_family = AF_INET;
  outgoing.sin_port = htons(9000);
  int erg=::connect(dsc, (sockaddr*)(&outgoing), sizeof(outgoing));
  if (erg <0) { close(dsc); return 0; };

  return inited=1;
};

void yyysound_client_noexception::play(const string &p)
{
  while (write(dsc,"PLAY ",5)!=5);
  while (write(dsc,p.c_str(),p.length())!=int(p.length()));
  while (write(dsc," ",1)!=1);
};
