/*
 * imdbsearch.c: A plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id: i18n.c 1.3 2007/08/12 14:30:57 kls Exp $
 */

#include <getopt.h>
#include <vdr/plugin.h>
#include <vdr/menu.h>
#include <vdr/status.h>
#include <vdr/osd.h>
#include <vdr/tools.h>
#include <vdr/videodir.h>
#include "i18n.h"

static const char *VERSION        = "0.3.6";
static const char *DESCRIPTION    = "Searches the IMDb";
static const char *MAINMENUENTRY  = "IMDb-Search";

//Globals
int hide=0;
int live=0;
int replace=0;
int getimages=0;
char strImagesDir[255];


int channelModifier=0;
bool eventToggle=false;
bool mayToggle=true;
cEvent* event;
cChannel* prevChannel;
cChannel* nextChannel;

//------------------cImdbSearch-------------------------------
class cImdbSearch{
private:
	cChannel* currentChannel;
	char *text;
	const char *replayingPath;
	const cEvent *current;
	void GetTitle(void);
	char file;
	int realEventID;

public:
	cImdbSearch(void);
  };



cImdbSearch::cImdbSearch(void)
{
	dsyslog("IMDb-Search: Starting search");
	//reset them all
	replayingPath=NULL;
	event=NULL;
	prevChannel=NULL;
	nextChannel=NULL;
	mayToggle=true;
	//Running dvbplayer or LiveBuffer on currentDevice
	if (cDevice::PrimaryDevice()->Replaying() && live==0)
	{
		#if VDRVERSNUM >= 10403
		replayingPath=cReplayControl::NowReplaying();
		#else
		replayingPath=cControl::Control()?cReplayControl::LastReplayed():NULL;
		#endif
	}
	
	//replaying dvb
	if (replayingPath != NULL)
	{
		dsyslog("IMDb-Search: Replaying path %s", replayingPath);
		mayToggle=false;
		cRecording *recording = Recordings.GetByName(replayingPath);
		const cRecordingInfo *info = recording->Info();

		event=new cEvent(999999);
		event->SetTitle(info->Title());
		event->SetShortText(info->ShortText());
		event->SetComponents((cComponents *)info->Components());
		dsyslog("IMDb-Search: Replaying %s", event->Title());
	}
	else
	{
	  	GetTitle();
	}

	//build and execute command
	char *command;
	char *calltype;
	int i;
	if (live==1)
	{
		if (getimages==0)
		{
			calltype="VDRPLUGIN_LIVE_NOIMG";
		}
		else
		{
			calltype="VDRPLUGIN_LIVE";
		}
	}
	else
	{
		if (getimages==0)
		{
			calltype="VDRPLUGIN_NOIMG";
		}
		else
		{
			calltype="VDRPLUGIN";
		}
	}
	if (event)
	{
		asprintf(&command, "imdb-search.sh \"%s\" %s",event->Title(),calltype);
		Skins.Message(mtStatus, tr("Checking IMDb..."));
		dsyslog("IMDb-Search: Script-command: %s",command);
		i=system(command);
		free(command);
		Skins.Message(mtStatus,NULL);
	}
	else
	{
		i=256;
	}
	//process answer
	//no data
	if (i==256)
	{
		dsyslog("IMDb-Search: No data");
		Skins.Message(mtError, tr("No data found!"));
	}
	else
	{
		//mplayer running
		if (i==512)
		{
			dsyslog("IMDb-Search: mplayer running");
			mayToggle=false;
			event=NULL;
			event= new cEvent(999999);
			event->SetTitle(tr ("MPlayer-Replay"));
			prevChannel=NULL;
			nextChannel=NULL;
		}
		
		dsyslog("IMDb-Search: Loading moviedata");	
		long lSize;		
		FILE* f;
		f = fopen("/tmp/moviedata", "r");
		fseek(f,0,SEEK_END);
		lSize=ftell(f);
		rewind(f);
		text= (char*) malloc (sizeof(char)*lSize);
		fread (text,1,lSize,f);
		fclose(f);	
		event->SetDescription(text);
	}
	if (event && getimages==1)
	{
		dsyslog("IMDb-Search: Moving image");
		char *copycommand;
		if (realEventID != 0)
		{
			asprintf(&copycommand, "cp /tmp/img.jpg %s/%i.jpg 2>/dev/null",strImagesDir,realEventID);
			system(copycommand);
			free(copycommand);
		}
		asprintf(&copycommand, "mv /tmp/img.jpg %s/%i.jpg 2>/dev/null",strImagesDir,event->EventID());
		int i=system(copycommand);
		free(copycommand);
		if (i != 0 )
		{
			asprintf(&copycommand, "rm  %s/999999.jpg 2>/dev/null",strImagesDir);
			system(copycommand);
			free(copycommand);
		}
		
	}	
}


void cImdbSearch::GetTitle(void)
{
	dsyslog("IMDb-Search: Getting title");
	currentChannel =  Channels.GetByNumber(cDevice::PrimaryDevice()->CurrentChannel()+channelModifier);
	prevChannel = Channels.GetByNumber(cDevice::PrimaryDevice()->CurrentChannel()-1+channelModifier);
	nextChannel = Channels.GetByNumber(cDevice::PrimaryDevice()->CurrentChannel()+1+channelModifier);
	cSchedulesLock SchedulesLock;
	const cSchedules *Schedules = cSchedules::Schedules(SchedulesLock);
	const cSchedule *Schedule = Schedules->GetSchedule(Channels.GetByNumber(currentChannel->Number())->GetChannelID());
	current=NULL;
	event=NULL;
	if (eventToggle && Schedule)
	{
		current=Schedule->GetFollowingEvent();
	}
	else if (!eventToggle && Schedule)
	{
		current=Schedule->GetPresentEvent();
	}
        if (current) 
	{	
		if (replace == 1)
		{
			event = (cEvent *)current;
		}
		else
		{
			realEventID=current->EventID();
			event = new cEvent(999999);
			event->SetTitle(current->Title());
			event->SetStartTime(current->StartTime());
			event->SetDuration(current->Duration());
			event->SetShortText(current->ShortText());
			event->SetDescription(current->Description());
			event->SetComponents((cComponents *) current->Components());
			dsyslog("IMDb-Search: Title is %s",event->Title());
		}
	}
	
}



// --- cImdbSearchDisplay --------------------------------------------------------
class cImdbSearchDisplay : public cOsdMenu {
private:

public:
  cImdbSearchDisplay();
  virtual ~cImdbSearchDisplay();
  virtual void Display(void);
  virtual eOSState ProcessKey(eKeys Key);
  };


cImdbSearchDisplay::cImdbSearchDisplay()
:cOsdMenu(tr("IMDb-Info"))
{
	Display();
}



cImdbSearchDisplay::~cImdbSearchDisplay()
{
	
}

void cImdbSearchDisplay::Display()
{
  SetHelp(strdup(prevChannel ? prevChannel->Name() : ""),
	  strdup( eventToggle && mayToggle ? "<<" : ""),
	  strdup(!eventToggle && mayToggle ? ">>" : ""),
	  strdup(nextChannel ? nextChannel->Name() : ""));
  cOsdMenu::Display();
  if (event) DisplayMenu()->SetEvent(event);
  if (event) cStatus::MsgOsdTextItem(event->Title());
}

eOSState cImdbSearchDisplay::ProcessKey(eKeys Key)
{
  switch (Key) {
    case kUp|k_Repeat:
    case kUp:
    case kDown|k_Repeat:
    case kDown:
    case kLeft|k_Repeat:
    case kLeft:
    case kRight|k_Repeat:
    case kRight:
         DisplayMenu()->Scroll(NORMALKEY(Key) == kUp || NORMALKEY(Key) == kLeft, NORMALKEY(Key) == kLeft || NORMALKEY(Key) == kRight);
         return osContinue;
    default:
         break;
    }

  eOSState state = cOsdMenu::ProcessKey(Key);

  if (state == osUnknown) {
     switch (Key) {
       case kOk:
            return osBack;
	case kRed:
		if (prevChannel)
		{
			channelModifier--;
			new cImdbSearch();
			Display();
		}
		break;
	case kGreen:
		if (eventToggle && mayToggle)
		{
			eventToggle=!eventToggle;
			new cImdbSearch();
			Display();
		}
		break;
	case kYellow:
		if (!eventToggle && mayToggle)
		{
			eventToggle=!eventToggle;
			new cImdbSearch();
			Display();
		}
		break;
	case kBlue:
		if (nextChannel)
		{
			channelModifier++;
			new cImdbSearch();
			Display();
		}
		break;
       default:
            state = osContinue;
       }
     state = osContinue;
     }
  return state;
}

// --- cPluginImdbSearch --------------------------------------------------------

class cPluginImdbSearch : public cPlugin 
{
	private:
		bool fImagesDirSet;
	public:
		cPluginImdbSearch(void);
		virtual ~cPluginImdbSearch();
		virtual const char *Version(void) { return VERSION; }
		virtual const char *Description(void) { return DESCRIPTION; }
		virtual const char *CommandLineHelp(void);
		virtual bool ProcessArgs(int argc, char *argv[]);
		virtual bool Start(void);
		virtual void Housekeeping(void);
		virtual const char *MainMenuEntry(void) { return (hide ? NULL : tr(MAINMENUENTRY)); }
		virtual cOsdObject *MainMenuAction(void);
		virtual cMenuSetupPage *SetupMenu(void);
		virtual bool SetupParse(const char *Name, const char *Value);
		virtual cString SVDRPCommand(const char *Command, const char *Option, int &ReplyCode);
};


cPluginImdbSearch::cPluginImdbSearch(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!
	fImagesDirSet = false;
}

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

const char *cPluginImdbSearch::CommandLineHelp(void)
{
  // Return a string that describes all known command line options.
  return "  -i <IMAGESDIR>, --epgimages=<IMAGESDIR> Set directory where epgimages are stored\n";
}

bool cPluginImdbSearch::ProcessArgs(int argc, char *argv[])
{
  // Implement command line argument processing here if applicable.
	static const struct option long_options[] = {
		{ "epgimages", required_argument, NULL, 'i' },
		{ NULL }
	};

	int c;
	while ((c = getopt_long(argc, argv, "i:", long_options, NULL)) != -1)
	{
		switch (c) 
		{
			case 'i':
        			strncpy(strImagesDir, optarg, sizeof(strImagesDir));
        			fImagesDirSet = true;
        			break;
			default:
				return false;
		}
	}
	return true;
}

bool cPluginImdbSearch::Start(void)
{
	// Start any background activities the plugin shall perform.
	RegisterI18n(Phrases);
	if (!fImagesDirSet) 
	{
		// set epgimages directory
		char *dir = NULL;
		asprintf(&dir, "%s/epgimages", VideoDirectory);
		//asprintf(&dir, "%s/epgimages", cPlugin::ConfigDirectory(PLUGIN_NAME_I18N));
		if (dir) 
		{
			strncpy(strImagesDir, dir, sizeof(strImagesDir));
			fImagesDirSet = true;
			free(dir);
		}
	}
	return true;
}

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

cOsdObject *cPluginImdbSearch::MainMenuAction(void)
{
	// Perform the action when selected from the main VDR menu.
	channelModifier=0;
	eventToggle=false;
	new cImdbSearch();  
	if (event)
	{
		return new cImdbSearchDisplay();
	}
	else
	{
		return NULL;
	}
  

}

cString cPluginImdbSearch::SVDRPCommand(const char *Command, const char *Option, int &ReplyCode)
{
  return NULL;
}

// --- cMenuSetupImdbSearch --------------------------------------------------------
class cMenuSetupImdbSearch : public cMenuSetupPage {
 public:
  cMenuSetupImdbSearch(void);
 protected:
  virtual void Store(void);
 private:
 	int new_hide;
	int new_live;
	int new_replace;
	int new_getimages;
};

cMenuSetupImdbSearch::cMenuSetupImdbSearch(void)
{
	new_hide = hide;    
	Add(new cMenuEditBoolItem(tr("Hide main menu entry"), &hide, tr("no"), tr("yes")));
	Add(new cMenuEditBoolItem(tr("Live-Entry despite replay"), &live, tr("no"), tr("yes")));
	Add(new cMenuEditBoolItem(tr("Replace original info (temporarily)"), &replace, tr("no"), tr("yes")));
	Add(new cMenuEditBoolItem(tr("Download EPG-Images"), &getimages, tr("no"), tr("yes")));
}

void cMenuSetupImdbSearch::Store(void)
{
	SetupStore("HideMenu", new_hide = hide);
	SetupStore("LiveEntry", new_live=live);
	SetupStore("ReplaceInfo", new_replace=replace);
	SetupStore("GetImages", new_getimages=getimages);	
}

cMenuSetupPage *cPluginImdbSearch::SetupMenu(void)
{
  // Return a setup menu in case the plugin supports one.
  return new cMenuSetupImdbSearch();
}

bool cPluginImdbSearch::SetupParse(const char *Name, const char *Value)
{
	// Parse your own setup parameters and store their values.
	if (!strcasecmp(Name, "HideMenu"))
		hide = atoi(Value);
	if (!strcasecmp(Name, "LiveEntry"))
		live = atoi(Value);
	if (!strcasecmp(Name, "ReplaceInfo"))
		replace=atoi(Value);
	if (!strcasecmp(Name, "GetImages"))
		getimages=atoi(Value);
	
  return true;
}


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