/*
 * event und message handler
 */

#include <unistd.h>
#include <vdr/plugin.h>
#include <vdr/timers.h>
#include "sock.h"
#include "select.h"
#include "vdrmonthread.h"
#include "helpers.h"

bool cHandler::HandleNewClient(cVdrmonClientSocket * sock)
{
  time_t starttime;
  sock->PutLine(cHelpers::GetRunningRecordings());
  sock->PutLine(cHelpers::GetNextRecordings(starttime));
  return true;
}

bool cHandler::HandleVdrEvent(cVdrmonClientSocket * sock, string& msg)
{
  msg = "";

  while(sock->Read())
  {
    // get lines
    while (sock->IsLineComplete())
    {
      string line;
      sock->GetLine(line);

      // some sanity checks here
      if (line.length() < 4)
        continue;

      // parse request
      string cmd = line.substr(0, 4);

      // handle request: we simply pass all events
      msg += line + "\n";
    }
  }

  return true;
}

bool cHandler::HandleClientRequest(cVdrmonClientSocket * sock)
{
  while(sock->Read())
  {
    // get lines
    while (sock->IsLineComplete())
    {
      string line;
      sock->GetLine(line);

      // some sanity checks here
      if (line.length() < 4)
        continue;

      // parse request
      string cmd = cHelpers::ToUpper(line.substr(0, 4));

      // handle request
      if (cmd == "GETR")
      {
 	string text = cHelpers::GetRunningRecordings();
        sock->PutLine(text);
      }
      else if (cmd == "GETN")
      {
	time_t starttime;
 	string text = cHelpers::GetNextRecordings(starttime);
        sock->PutLine(text);
      }
      else if (cmd == "QUIT")
      {
        // close socket
        sock->PutLine(string("Good bye! :-)\n"));
        sock->Disconnect();
      }
      else if (cmd == "PLYS")
      {
	// what's playing?
	sock->PutLine(GetPlays());
      }
      else if (cmd == "ALIV")
      {
	// query alive answer
	sock->PutLine("ALIV\n");
      }
    }
  }

  return true;
}

string cHandler::GetPlays()
{
  string title;
  if (cVdrmonThread::Plays(title))
    return "PLAY " + title + "\n";
  else
    return string("NPLY\n");
}
