/*
 * pluginsetup.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 <vdr/plugin.h>

#define MAX_ENTRIES 256
#define MAX_LISTITEMS 32

static const char *VERSION        = "0.0.6";
static const char *DESCRIPTION    = "Plugin Setup";
static const char *MAINMENUENTRY  = NULL;

static const char *CFG_FILE="plugin_setup.conf";
static const char *SCRIPT_FILE="plugin_setup_runvdr.conf";

typedef struct _man
{
	char *scriptName;
	int value;
	char *desc;
	const char * lItems[MAX_LISTITEMS];
} MANAGER_ENTRY;


// --- cMenuSetupManager --------------------------------------------------------

class cMenuSetupManager : public cMenuSetupPage
{
private:
   MANAGER_ENTRY *manTable[ MAX_ENTRIES ];
   char configFile[254];
   char scriptFile[254];
   int numEntries;
   void FreeTable(int);
   void makeNewRunvdrConf(void);
protected:
   virtual void Store(void);
public:
   cMenuSetupManager(const char *configFile, const char *scrFile);
};	

void cMenuSetupManager::makeNewRunvdrConf(void)
{
   int i, j;
   FILE *fhdl = fopen(scriptFile, "w" );

   for( j=1; j <= numEntries; j++ )
   {
      for( i=0; i < numEntries && manTable[i] != NULL; i++ )
      {
   	  if(manTable[i]->value == j)
      	       fprintf(fhdl, " -P \"%s\" ", manTable[i]->scriptName);
      }
   }
   fclose(fhdl);
}

cMenuSetupManager::cMenuSetupManager(const char *cfgFile, const char *scrFile)
{
   int i = 0;
	 int currItem = 1;

   bool bErr = false;

   if( cfgFile == NULL )
      strcpy(configFile,AddDirectory( cPlugin::ConfigDirectory(), CFG_FILE ));
   else
      strcpy(configFile,cfgFile);

   if( scrFile == NULL )
      strcpy(scriptFile,AddDirectory( cPlugin::ConfigDirectory(), SCRIPT_FILE ));
   else
      strcpy(scriptFile,scrFile);

   numEntries = 0;
//   printf( "CfgFile: %s\n", configFile );
//   printf( "ScriptFile: %s\n", scriptFile );

   FILE *fhdl = fopen( configFile, "r" );
//   printf( "Open: %s\n", configFile );
   static char buffer[ 2048 ];

   SetSection( "Plugin Manager" );
   while( fgets( buffer, sizeof( buffer ), fhdl ) != NULL )
   {
      if( buffer[0] != '#' )
      {
         if( bErr == false )
         {
            manTable[i]=( MANAGER_ENTRY * )calloc( sizeof( MANAGER_ENTRY ), 1 );
         }
         else
         {
            FreeTable( i );
            bErr = false;
         }
	//<startno>:<name+param>:<description>:
//         printf( "\n%s", buffer );
         manTable[i]->value = -1;
         //sscanf( buffer, "%d::%a[^::]::%a[^::]::",
        sscanf( buffer, "%d&&%a[^&&]&&%a[^&&]&&",
                 &(manTable[i]->value),
                 &(manTable[i]->scriptName),
                 &(manTable[i]->desc ) );


         if( manTable[i]->value >= 0 && manTable[i]->value < MAX_ENTRIES && manTable[i]->scriptName != NULL && manTable[i]->desc != NULL )
         {
//            printf( "%d\n", manTable[i]->value );
//            printf( "%s\n", manTable[i]->scriptName );
//            printf( "%s\n", manTable[i]->desc );
            i++;
         }
         else
            bErr = true;
      }
   };
   numEntries=i;
   manTable[numEntries]=NULL;

   //nach Priorität in Liste schreiben:
	 for(currItem=1; currItem<=numEntries; currItem++ )
   {
      for( i=0; i<numEntries; i++)
			{ 	
  				if( manTable[i]->value > numEntries )
   	  		 	manTable[i]->value = numEntries;

					if(manTable[i]->value == currItem)
         		Add(new cMenuEditIntItem( manTable[i]->desc, &(manTable[i]->value), 0, numEntries ));
			}
   }
   //alle mit Prioriät '0' hinterher:
	 for( i=0; i<numEntries; i++)
			if(manTable[i]->value == 0)
				Add(new cMenuEditIntItem( manTable[i]->desc, &(manTable[i]->value), 0, numEntries ));

   fclose( fhdl );
}

void cMenuSetupManager::Store(void)
{
   int i;
   FILE *fhdl = fopen( configFile, "w" );
//   printf( "Store called\n" );

   makeNewRunvdrConf();

   fprintf( fhdl, "# This file contains the plugins\n" );
   fprintf( fhdl, "# Syntax:\n" );
   fprintf( fhdl, "# <startno>::<name+param>::<description>::\n" );

   for( i=0; i < numEntries && manTable[i] != NULL; i++ )
   {
      //fprintf( fhdl, "%d::%s::%s::\n",
      fprintf( fhdl, "%d&&%s&&%s&&\n",
                     (manTable[i]->value),
                     (manTable[i]->scriptName),
                     (manTable[i]->desc ) );
      FreeTable( i );
      free( manTable[ i ] );
   }
   fclose( fhdl );
}

void cMenuSetupManager::FreeTable( int idx )
{
   if( manTable[idx]->scriptName != NULL )
   {
      free( manTable[idx]->scriptName );
      manTable[idx]->scriptName = NULL;
   }

   if( manTable[idx]->desc != NULL )
   {
      free( manTable[idx]->desc );
      manTable[idx]->desc = NULL;
   }
}

// --- cPluginPluginsetup ----------------------------------------------------------

class cPluginPluginsetup : public cPlugin {
private:
  // Add any member variables or functions you may need here.
   const char *configFile;
   const char *scriptFile;
public:
  cPluginPluginsetup(void);
  virtual ~cPluginPluginsetup();
  virtual const char *Version(void) { return VERSION; }
  virtual const char *Description(void) { return tr(DESCRIPTION); }
  virtual const char *CommandLineHelp(void);
  virtual bool ProcessArgs(int argc, char *argv[]);
  //virtual bool Initialize(void);
  virtual bool Start(void);
  virtual void Housekeeping(void);
  virtual const char *MainMenuEntry(void) { return MAINMENUENTRY; }
  //virtual cOsdObject *MainMenuAction(void);
  virtual cMenuSetupPage *SetupMenu(void);
  //virtual bool SetupParse(const char *Name, const char *Value);
  };

cPluginPluginsetup::cPluginPluginsetup(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!
  configFile=NULL;
  scriptFile=NULL;
}

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

const char *cPluginPluginsetup::CommandLineHelp(void)
{
  // Return a string that describes all known command line options.
   static char *help_str=0;

   free( help_str );

   asprintf( &help_str, "  -c FILE,  --cfgFile=FILE  name of configuration file\n"
                        "            (default: %s)\n"
                        "  -x FILE,  --execFile=FILE  name of script file\n"
                        "            (default: %s)\n",
             configFile, scriptFile );
   return help_str;
}

bool cPluginPluginsetup::ProcessArgs(int argc, char *argv[])
{
   static struct option long_options[] = {
      { "cfgFile", required_argument, NULL, 'c'},
      { "execFile", required_argument, NULL, 'x'},
      { NULL}};

   int c, option_index = 0;

   while( ( c = getopt_long( argc, argv, "c:", long_options, &option_index ) ) != -1 )
   {
      switch( c )
      {
         case 'c':  configFile=optarg; break;
         case 'x':  scriptFile=optarg; break;
         default:  return false;
      }
   }

   return true;
}

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

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

cMenuSetupPage *cPluginPluginsetup::SetupMenu(void)
{
  // Return a setup menu in case the plugin supports one.
     //return new cMenuSetupManager(configFile,scriptFile);
     return new cMenuSetupManager(configFile,scriptFile);
}

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