/*
 * vbox.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 <vdr/plugin.h>
#include <vdr/osd.h>
#if VDRVERSNUM >= 10307
#include <vdr/interface.h>
#include <vdr/skins.h>
#endif

#include <vdr/status.h>
#include "menu-vbox.h"
#include "setup.h"
#include "i18n.h"
#include "debug.h"

static const char *VERSION        = "0.5.1";
static const char *DESCRIPTION    = "Client for the 'vbox'";
static const char *MAINMENUENTRY  = "VBOX";

cVBOXSetup g_VBOXSetup;

class cPluginVbox : public cPlugin {
private:
  // Add any member variables or functions you may need here.
  cVBOXUserlist m_VBOXUserlist;
  char * m_szNotificationText;
  time_t m_timeLastVBOXMenuAccess;
  
public:
  cPluginVbox(void);
  virtual ~cPluginVbox();
  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 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);
protected:
   char * _GetNotificationText();
   void _CheckForNewMessages(void);

  };

cPluginVbox::cPluginVbox(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!
	m_szNotificationText = NULL;
	m_timeLastVBOXMenuAccess = 0;
}

cPluginVbox::~cPluginVbox()
{
  // Clean up after yourself!
	if(m_szNotificationText)
		free(m_szNotificationText);
}

const char *cPluginVbox::CommandLineHelp(void)
{
 // Return a string that describes all known command line options.
  return "  -r SCRIPT,   --resolvenumber=SCRIPT      Script to resolve names from numbers\n";
}

bool cPluginVbox::ProcessArgs(int argc, char *argv[])
{
  static struct option long_options[] = {
      { "resolvenumber",    required_argument, NULL, 'r' },
       { NULL }
    };

  int c, option_index = 0;
  while((c=getopt_long(argc,argv,"r:",long_options,&option_index))!=-1) {
    switch (c) {
      case 'r': asprintf(&resolvenumber_script,"vbox:%s",optarg); break;

      default:  return false;
      }
    }
  return true;
}

bool cPluginVbox::Initialize(void)
{
  if(!m_VBOXUserlist.Load(AddDirectory(ConfigDirectory(),"vboxuser.conf"))) {
    // File load failed
    isyslog("vboxuser.conf file not found");
  }
  // Initialize any background activities the plugin shall perform.
  return true;
}

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

void cPluginVbox::Housekeeping(void)
{
  // Perform any cleanup or other regular tasks.
	Dprintf("housekeeping called\n");
	if(g_VBOXSetup.m_bNotifyAboutNewCalls)
	{
		_CheckForNewMessages();
        if(_GetNotificationText())
		{
            InfoMessage(_GetNotificationText());
		}
	}
}

cOsdObject *cPluginVbox::MainMenuAction(void)
{
 m_timeLastVBOXMenuAccess = time(NULL); // remember time, when vbox menu is opened. 
										//for the next 2 hours there will be no new calls message diplayed,
										// even if there are unread messages
										//if no newer calls will arrive in the meantime.
										// see _CheckForNewMessages()
  // Perform the action when selected from the main VDR menu.
 if(m_VBOXUserlist.Count() == 0)
 {
     ErrorMessage(tr("No VBOX users configured!"));

  return NULL;
 }	
 if(m_VBOXUserlist.Count() > 1)
 {
    return new cMenuVBOXUser(&m_VBOXUserlist);
 }
 if(m_VBOXUserlist.Count() == 1)
 {
    return new cMenuCtrlVBOX(m_VBOXUserlist.First());
 }
 Dprintf("return null\n");
 return NULL;
}

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

bool cPluginVbox::SetupParse(const char *Name, const char *Value)
{
  // Parse your own setup parameters and store their values.
	return g_VBOXSetup.Parse(Name, Value);
}


char * cPluginVbox::_GetNotificationText()
{
	return m_szNotificationText;
}

void cPluginVbox::_CheckForNewMessages()
{
	if(difftime (time(NULL),m_timeLastVBOXMenuAccess) > 60*60 *2 )
	{
		// 2 hours since last VBOXMenuAccess
		// reset m_timeLastVBOXMenuAccess so new calls message is displayed again, if new calls are there.
		m_timeLastVBOXMenuAccess = 0;
	}
	time_t TimeLatest=0;
	int Count = 0;
	cVBOXUser *pLatestMsgVBOXUser = NULL;
	// check which user has the latest new message
	cVBOXUser *pVBOXUser = NULL;
	for (pVBOXUser = m_VBOXUserlist.First(); pVBOXUser; pVBOXUser = m_VBOXUserlist.Next(pVBOXUser))
	{
		time_t tempTimeLatest;
		int tempCount = 0;
		if(pVBOXUser->GetServerNewMsgCount(&tempCount,&tempTimeLatest))
		{
			
			if(tempCount > 0 && tempTimeLatest>TimeLatest)
			{
				// this user has new msgs and his latest msg is newer than of the latest user before
				Count = tempCount;
				TimeLatest = tempTimeLatest;
				pLatestMsgVBOXUser = pVBOXUser;
			}
		}
	}

	if(pLatestMsgVBOXUser && (m_timeLastVBOXMenuAccess < TimeLatest))
	{
		if(m_szNotificationText)
			free(m_szNotificationText);
		asprintf(&m_szNotificationText,tr("VBOX-User %s has %d new call(s)"),pLatestMsgVBOXUser->Name(),Count);

	}
	else
	{
		if(m_szNotificationText)
			free(m_szNotificationText);
		m_szNotificationText = NULL;
	}


}

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