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

#include <vdr/config.h>
#include <vdr/plugin.h>
#include <vdr/status.h>

static const char *VERSION        = "0.0.2";
static const char *DESCRIPTION    = "Saves current channel";

// --- cStatusMonitor -------------------------------------------------------

class cStatusMonitor:public cStatus {
private:
  const char *channelfilename;
  int channel;
protected:
  virtual void ChannelSwitch(const cDevice *Device, int ChannelNumber);
public:
  cStatusMonitor();
};

cStatusMonitor::cStatusMonitor()
{
  channelfilename=strdup(AddDirectory(cPlugin::ConfigDirectory(),"savechannel.conf"));
  channel=-1;
  FILE *f=fopen(channelfilename,"r");
  if(f) {
    if (fscanf(f,"%d",&channel)==1) { 
      isyslog("Read channel %d from %s",channel,channelfilename); 
      Setup.CurrentChannel=channel;
    } else esyslog("couldn't read channel no. from %s",channelfilename);
    fclose(f);
  } else esyslog("Couldn't open file %s: %s",channelfilename,strerror(errno));
}

void cStatusMonitor::ChannelSwitch(const cDevice *Device, int ChannelNumber)
{
  if (ChannelNumber) {
    if (Device==cDevice::PrimaryDevice() && ChannelNumber != channel) {
      esyslog("savechannel: saving channel %d",ChannelNumber);
      cSafeFile f(channelfilename);
      if (f.Open()) {
        fprintf(f,"%d",ChannelNumber);
        f.Close();
        channel=ChannelNumber;
      } else LOG_ERROR;
    }
  }
}

// --- cPluginSavechannel ---------------------------------------------------

class cPluginSavechannel : public cPlugin {
private:
  // Add any member variables or functions you may need here.
  cStatusMonitor *statusMonitor;
public:
  cPluginSavechannel(void);
  virtual ~cPluginSavechannel();
  virtual const char *Version(void) { return VERSION; }
  virtual const char *Description(void) { return DESCRIPTION; }
  virtual bool Start(void);
  virtual void Stop(void);
  };

cPluginSavechannel::cPluginSavechannel(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!
  statusMonitor = NULL;
}

cPluginSavechannel::~cPluginSavechannel()
{
  // Clean up after yourself!
}

bool cPluginSavechannel::Start(void)
{
  // Start any background activities the plugin shall perform.
  statusMonitor = new cStatusMonitor;
  return true;
}

void cPluginSavechannel::Stop(void)
{
  // Stop any background activities the plugin shall perform.
  delete statusMonitor;
}

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