/*
 * VdrmonThread
 */
#include <string.h>
#include <vdr/plugin.h>
#include <vdr/thread.h>
#include "vdrmonthread.h"
#include "select.h"
#include "helpers.h"

bool cVdrmonThread::plays;
string cVdrmonThread::playname = "";

cVdrmonThread::cVdrmonThread(int port)
{
  pipe[0] = pipe[1] = -1;
  select = NULL;
  this->port = port;
  records = 0;
  plays = false;
  playname = "";
}

cVdrmonThread::~cVdrmonThread()
{
  Cleanup();
}

void cVdrmonThread::Action(void)
{
  // create listener socket
  if (!Init())
    return;

  // do processing
  select->Action();

  // cleanup
  Cleanup();
}

bool cVdrmonThread::Init()
{
  // create select
  select = new cSelect();
  if (select == NULL)
    return false;

  // create server socket
  cVdrmonServerSocket * sock = new cVdrmonServerSocket();
  if (sock == NULL || !sock->Create(port))
    return false;

  // create pipe for communication with plugin the thread
  if (::pipe(pipe) < 0) {
    LOG_ERROR;
    return false;
  }

  // register pipe for select
  select->SetEventPipe(pipe);

  // register server socket
  select->SetServerSocket(sock);

  return true;
}

void cVdrmonThread::Cleanup()
{
  if (pipe[0] != -1)
    close(pipe[0]);
  if (pipe[1] != -1)
    close(pipe[1]);
  if (select)
    delete select;
}

void cVdrmonThread::Shutdown()
{
  // close write side of the pipe. this wakes the thread up
  close(pipe[1]);
  pipe[1] = -1;
}

int cVdrmonThread::GetVdrPipe()
{
  return pipe[1];
}

void cVdrmonThread::Recording(const char * name)
{
  select->DispatchVdrEvent(cHelpers::GetRunningRecordings());
}

void cVdrmonThread::Replaying(const char * name)
{
  if (name  == NULL)
  {
    plays = false;
    playname = "";
    select->DispatchVdrEvent(string("ENDP\n"));
  }
  else
  {
    plays = true;
    playname = name;
    select->DispatchVdrEvent(string("BEGP ") + name + "\n");
  }
}

bool cVdrmonThread::Plays(string& name)
{
  name = playname;
  return plays;
}
