/*
 * Otv4vdr.c: A plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id$
 */

#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>

#include <vdr/interface.h>
#include <vdr/plugin.h>
#include <vdr/menuitems.h>
#include <vdr/status.h>
#include <vdr/thread.h>

#include "otv4vdr.h"
#include "i18n.h"
#include "opts.h"  // From Sc plugin 

static cOpts *Otv4vdrOpts;
static int   ChannelEPGSource; 

cPluginOtv4vdr * thePluginOtv4vdr;


// --- cMenuSetupOtv4vdr ------------------------------------------------------------

cMenuSetupOtv4vdr::cMenuSetupOtv4vdr(const char *CfgDir)
{
  cfgdir=strdup(CfgDir);
  SetSection(tr(OTV4VDR));
  Otv4vdrOpts->Backup(); 
  Otv4vdrOpts->Create(this);
}

cMenuSetupOtv4vdr::~cMenuSetupOtv4vdr()
{
  free(cfgdir);
}

void cMenuSetupOtv4vdr::Store(void)
{
  Otv4vdrOpts->Store();
}

eOSState cMenuSetupOtv4vdr::ProcessKey(eKeys Key)
{
  eOSState state = cOsdMenu::ProcessKey(Key);

  switch(state) {
    case osUnknown:
      if(Key==kOk) { Store(); state=osBack; }
      break;

    default:
      break;
    }
  return state;
}

// --- cOtv4vdrSetup ---------------------------------------------------------------

cOtv4vdrSetup Otv4vdrSetup;

cOtv4vdrSetup::cOtv4vdrSetup(void)
{
}



// --- cPluginOtv4vdr ----------------------------------------------------------

cPluginOtv4vdr::cPluginOtv4vdr(void)
{
  // Initialize any member variables here.
  // DON'T DO ANYTHING ELSE THAT MAY HAVE SIDE EFFECTS, REQUIRE GLOBAL
  // VDR OBJECTS TO EXIST OR PRODUCE ANY OUTPUT!

  thePluginOtv4vdr=this;
  UpdateProcess = NULL;
  ChannelEPGSource=0;
  Otv4vdrOpts=new cOpts(0,1);
  if ( Channels.MaxNumber() > 2 )
	  Otv4vdrOpts->Add(new cOptInt("ChannelSource" ,tr(CHANNEL) ,&ChannelEPGSource ,0 , Channels.MaxNumber() ));
  else
	// Sounds like Channels not initialized yet !!
	  Otv4vdrOpts->Add(new cOptInt("ChannelSource" ,tr(CHANNEL) ,&ChannelEPGSource ,0 , 2000 ));


}

cPluginOtv4vdr::~cPluginOtv4vdr()
{
  if (UpdateProcess)
      delete UpdateProcess;
}

const char *cPluginOtv4vdr::CommandLineHelp(void)
{
  // Return a string that describes all known command line options.
  return NULL;
}

bool cPluginOtv4vdr::ProcessArgs(int argc, char *argv[])
{
  // Implement command line argument processing here if applicable.
  return true;
}

bool cPluginOtv4vdr::Initialize(void)
{
  // Initialize any background activities the plugin shall perform.
  return true;
}

bool cPluginOtv4vdr::Start(void)
{
  // Start any background activities the plugin shall perform.
  RegisterI18n(Phrases);
  return true;
}


void cPluginOtv4vdr::Stop(void)
{
  // Stop any background activities the plugin shall perform.
}



void cPluginOtv4vdr::Housekeeping(void)
{
  // Perform any cleanup or other regular tasks.
}

cOsdObject *cPluginOtv4vdr::MainMenuAction(void)
{
  // Perform the action when selected from the main VDR menu.
  UpdateProcess = new cDoIt(ConfigDirectory(),ChannelEPGSource);
  UpdateProcess->Start();
  Interface->Confirm( tr(UPDATING), 3);
  return NULL;
}


cMenuSetupPage *cPluginOtv4vdr::SetupMenu(void)
{

  return new cMenuSetupOtv4vdr(ConfigDirectory());
}

bool cPluginOtv4vdr::SetupParse(const char *Name, const char *Value)
{
  if(!Otv4vdrOpts->Parse(Name,Value))
    return false;
  return true;
}


bool cPluginOtv4vdr::Service(const char *Id, void *Data)
{
  // Handle custom service requests from other plugins
  return false;
}

const char **cPluginOtv4vdr::SVDRPHelpPages(void)
{
  // Return help text for SVDRP commands this plugin implements
  return NULL;
}

cString cPluginOtv4vdr::SVDRPCommand(const char *Command, const char *Option, int &ReplyCode)
{
  // Process SVDRP commands this plugin implements
  return NULL;
}

// --- cDoIt ----------------------------------------------------------


cDoIt::cDoIt(const char * pcdir, int channel):
cThread("epg writer")
{
  strcpy(cconfigdirectory,pcdir);
  ichannelsource=channel;
}

cDoIt::~cDoIt()
{
}

void cDoIt::Action(void)
{
  char Msg1[400];
  char Msg2[400];
  char sysCall[500];

  int deviceNo = 0;
  int n = -1;
  int prev = -1;
  cChannel *channel;
  cDevice *devPtr=NULL;
  
  // Looking for device #2
  if ( cDevice::NumDevices() >1 )
	  devPtr=cDevice::GetDevice(1);
  if ( devPtr != NULL )
      {
      deviceNo = 1;
      Interface->Confirm( "The 2nd DVB device will be used", 3);
      }
  else 
	devPtr=cDevice::PrimaryDevice();
 
  // Channel switching
  prev = cDevice::CurrentChannel();
   
    int o = ichannelsource;
    if (o >= 1 && o <= Channels.MaxNumber())
           n = o;

     channel = Channels.GetByNumber(n);
     if (channel) {
         if  ( (channel->Frequency()) != 10873 ) {
                  n = -1;
              Interface->Confirm( tr(BAD_CHANNEL), 3);
	   } else {
      	   if (!devPtr->SwitchChannel(channel, true)) {
                     n=-1;
	              Interface->Confirm( tr(BAD_CHANNEL), 3);
                	esyslog("Plugin Otv4vdr: Error switching to channel");
              	}
	   }
        } else {
               n=-1;
              Interface->Confirm( tr(BAD_CHANNEL), 3);
        	esyslog("Plugin Otv4vdr: Unable to find channel");
        	}

 if ( n>0 ){
  strcpy(Msg1,tr(DOWNLOADED));
  strcpy(Msg2,tr(ERR_DOWNLOADED));
  strcpy(sysCall,cconfigdirectory);
  strcat(sysCall,"/otv4vdr/Download.sh ");
  strcat(sysCall,cconfigdirectory);
  strcat(sysCall," ");
  strcat(sysCall,Msg1);
  strcat(sysCall," ");
  strcat(sysCall,Msg2);
  strcat(sysCall," ");
  if (deviceNo == 0)
	  strcat(sysCall,"0");
  else
	  strcat(sysCall,"1");
  strcat(sysCall," ");
  SystemExec(sysCall);

  n=prev;
  channel = Channels.GetByNumber(n);
  if (channel) {
        	if (!devPtr->SwitchChannel(channel, true)) {
	                Interface->Confirm( tr(BAD_CHANNEL), 3);
                	esyslog("Plugin Otv4vdr: Error switching to channel");
              	}
        } else {
                Interface->Confirm( tr(BAD_CHANNEL), 3);
        	esyslog("Plugin Otv4vdr: Unable to find channel");
        	}

  strcpy(Msg1,tr(UPDATED));
  strcpy(sysCall,cconfigdirectory);
  strcat(sysCall,"/otv4vdr/Parse.sh ");
  strcat(sysCall,cconfigdirectory);
  strcat(sysCall," ");
  strcat(sysCall,Msg1);
  strcat(sysCall," &");
  SystemExec(sysCall);
}
}

VDRPLUGINCREATOR(cPluginOtv4vdr); // Don't touch this!
