#include "epgsearchsetup.h"
#include "epgsearchcfg.h"
#include "searchtimer_thread.h"
#include "tools.h"
#include "changrp.h"
#include "menu_dirselect.h" 
#include "menu_searchtemplate.h"
#include "menu_blacklists.h"
#include "templatefile.h"

const char *RedKeyMode[2];
const char *BlueKeyMode[2];
const char *ProgressbarMode[4];
const char *StartMenuMode[2];
const char *AddSubtitleMode[3];

#define REDBUTTON (data.SetupMode?tr("Button$Standard"):tr("Button$Extended"))

cMenuEPGSearchSetup::cMenuEPGSearchSetup(void)
{
  RedKeyMode[0] = tr("Standard");
  RedKeyMode[1] = tr("Commands");

  BlueKeyMode[0] = tr("Standard");
  BlueKeyMode[1] = tr("Button$Search");

  ProgressbarMode[0] = tr("no");
  ProgressbarMode[1] = tr("pipes");
  ProgressbarMode[2] = tr("graphical");

  StartMenuMode[0] = tr("Button$Schedule");
  StartMenuMode[1] = tr("Button$Now");

  AddSubtitleMode[0] = tr("never");
  AddSubtitleMode[1] = tr("always");
  AddSubtitleMode[2] = tr("smart");

  Setup();
}

void cMenuEPGSearchSetup::Setup(void)
{
  data = EPGSearchConfig;
  if (isempty(EPGSearchConfig.mainmenuentry))
	strcpy(data.mainmenuentry,tr("Program guide"));

  Set();
  SetHelp(REDBUTTON, NULL, NULL, NULL);
}

void cMenuEPGSearchSetup::Set()
{
  int current = Current();
  Clear();
  Add(new cMenuEditBoolItem(tr("Hide main menu entry"),         &data.hidemenu,       tr("no"),      tr("yes")));
  if (!data.hidemenu)
      Add(new cMenuEditStrItem(IndentMenuItem(tr("Main menu entry")), data.mainmenuentry, sizeof(data.mainmenuentry), tr(AllowedChars)));

  Add(new cMenuEditBoolItem(tr("Replace original schedule"),    &data.ReplaceOrgSchedule, tr("no"),      tr("yes")));
  Add(new cMenuEditStraItem(tr("Start menu"), &data.StartMenu, 2, StartMenuMode));
  if (data.SetupMode)
  {
      Add(new cMenuEditStraItem(tr("Red key"), &data.redkeymode, 2, RedKeyMode));
      Add(new cMenuEditStraItem(tr("Blue key"), &data.bluekeymode, 2, BlueKeyMode));
      Add(new cMenuEditStraItem(tr("Show progress in 'Now'"),         &data.showProgress, 3, ProgressbarMode));
  }
  Add(new cMenuEditBoolItem(  tr("Show channel numbers"),         &data.showChannelNr,       tr("no"),      tr("yes")));
  Add(new cMenuEditBoolItem(  tr("Show channel separators"),         &data.showChannelGroups,       tr("no"),      tr("yes")));
  Add(new cMenuEditBoolItem(  tr("Show day separators"),         &data.showDaySeparators,       tr("no"),      tr("yes")));
  Add(new cMenuEditBoolItem(  tr("Show radio channels"),         &data.showRadioChannels,       tr("no"),      tr("yes")));
  Add(new cMenuEditBoolItem(  tr("'One press' timer creation"),         &data.onePressTimerCreation,       tr("no"),      tr("yes")));

  if (data.SetupMode)
  {
      Add(new cMenuEditBoolItem(  tr("Show channels without EPG"),         &data.showEmptyChannels,       tr("no"),      tr("yes")));
      Add(new cOsdItem(tr("Channel groups")));
      Add(new cMenuEditIntItem(tr("Time interval for FRew/FFwd [min]"), &data.timeShiftValue, 1, 9999));
      Add(new cMenuEditBoolItem(  tr("Toggle Green/Yellow"),         &data.toggleGreenYellow,       tr("no"),      tr("yes")));
      Add(new cMenuEditBoolItem(  tr("Ignore PayTV channels"),         &data.ignorePayTV,       tr("no"),      tr("yes")));
  }

  char* szUseUserTime = NULL;
  asprintf(&szUseUserTime, "%s %d", tr("Use user time"), 1);
  Add(new cMenuEditBoolItem(szUseUserTime, &data.ShowModes[showUserMode1].bUseIt,       tr("no"),      tr("yes")));
  if (data.ShowModes[showUserMode1].GetUsage())
  {
      Add(new cMenuEditStrItem(IndentMenuItem(tr("Description")), data.ShowModes[showUserMode1].szDescription, sizeof(data.ShowModes[showUserMode1].szDescription), tr(FileNameChars)));
      Add(new cMenuEditTimeItem(IndentMenuItem(tr("Time")), &data.ShowModes[showUserMode1].iTime));
  } 
  free(szUseUserTime);

  asprintf(&szUseUserTime, "%s %d", tr("Use user time"), 2);
  Add(new cMenuEditBoolItem( szUseUserTime, &data.ShowModes[showUserMode2].bUseIt,       tr("no"),      tr("yes")));
  if (data.ShowModes[showUserMode2].GetUsage())
  {
      Add(new cMenuEditStrItem(IndentMenuItem(tr("Description")), data.ShowModes[showUserMode2].szDescription, sizeof(data.ShowModes[showUserMode2].szDescription), tr(FileNameChars)));
      Add(new cMenuEditTimeItem(IndentMenuItem(tr("Time")), &data.ShowModes[showUserMode2].iTime));
  } 
  free(szUseUserTime);

  asprintf(&szUseUserTime, "%s %d", tr("Use user time"), 3);
  Add(new cMenuEditBoolItem(szUseUserTime, &data.ShowModes[showUserMode3].bUseIt,       tr("no"),      tr("yes")));
  if (data.ShowModes[showUserMode3].GetUsage())
  {
      Add(new cMenuEditStrItem(IndentMenuItem(tr("Description")), data.ShowModes[showUserMode3].szDescription, sizeof(data.ShowModes[showUserMode3].szDescription), tr(FileNameChars)));
      Add(new cMenuEditTimeItem(IndentMenuItem(tr("Time")), &data.ShowModes[showUserMode3].iTime));
  } 
  free(szUseUserTime);

  asprintf(&szUseUserTime, "%s %d", tr("Use user time"), 4);
  Add(new cMenuEditBoolItem(szUseUserTime, &data.ShowModes[showUserMode4].bUseIt,       tr("no"),      tr("yes")));
  if (data.ShowModes[showUserMode4].GetUsage())
  {
      Add(new cMenuEditStrItem(IndentMenuItem(tr("Description")), data.ShowModes[showUserMode4].szDescription, sizeof(data.ShowModes[showUserMode4].szDescription), tr(FileNameChars)));
      Add(new cMenuEditTimeItem(IndentMenuItem(tr("Time")), &data.ShowModes[showUserMode4].iTime));
  } 
  free(szUseUserTime);

  if (data.SetupMode)
  {
#if VDRVERSNUM && VDRVERSNUM >= 10331
      Add(new cMenuEditBoolItem(  tr("Use VDR's timer edit menu"),         &data.useVDRTimerEditMenu,       tr("no"),      tr("yes")));
#endif
      Add(new cMenuEditStrItem(tr("Default recording dir"), data.defrecdir, sizeof(data.defrecdir), tr(AllowedChars)));
      Add(new cMenuEditStraItem(tr("Add episode to manual timers"), &data.addSubtitleToTimer, 3, AddSubtitleMode));
      Add(new cOsdItem(tr("Blacklists")));
  }
  Add(new cMenuEditBoolItem(  tr("Use search timers"),         &data.useSearchTimers,       tr("no"),      tr("yes")));
  if (data.useSearchTimers)
  {
      Add(new cMenuEditIntItem(tr("  Update interval [min]"), &data.UpdateIntervall, 1, 9999));
      Add(new cMenuEditIntItem(tr("  SVDRP port"), &data.SVDRPPort, 1, 99999));

      Add(new cOsdItem(IndentMenuItem(tr("Search templates"))));
      Add(new cMenuEditBoolItem(IndentMenuItem(tr("Check timer conflicts")),         &data.checkTimerConflicts,       tr("no"),      tr("yes")));
      Add(new cMenuEditIntItem(IndentMenuItem(tr("Setup.Recording$Default priority")), &data.DefPriority, 0, MAXPRIORITY));
      Add(new cMenuEditIntItem(IndentMenuItem(tr("Setup.Recording$Default lifetime (d)")), &data.DefLifetime, 0, MAXLIFETIME));
      Add(new cMenuEditIntItem(IndentMenuItem(tr("Setup.Recording$Margin at start (min)")), &data.DefMarginStart));
      Add(new cMenuEditIntItem(IndentMenuItem(tr("Setup.Recording$Margin at stop (min)")), &data.DefMarginStop));
  }

  SetCurrent(Get(current));
  Display();
}

void cMenuEPGSearchSetup::Store(void)
{
    bool bRestart = false;
    if (EPGSearchConfig.useSearchTimers != data.useSearchTimers)
    {
	bRestart = true;
	cSearchTimerThread::Exit();
    }

    EPGSearchConfig = data;
    if (strcmp(EPGSearchConfig.mainmenuentry, tr("Program guide")) == 0) 
	strcpy(EPGSearchConfig.mainmenuentry,"");
    

    SetupStore("HideMenu",  EPGSearchConfig.hidemenu);
    SetupStore("MainMenuEntry",  EPGSearchConfig.mainmenuentry);
    SetupStore("ReplaceOrgSchedule",  EPGSearchConfig.ReplaceOrgSchedule);
    SetupStore("StartMenu",  EPGSearchConfig.StartMenu);
    SetupStore("RedKeyMode",  EPGSearchConfig.redkeymode);
    SetupStore("BlueKeyMode",  EPGSearchConfig.bluekeymode);
    SetupStore("ShowProgress",  EPGSearchConfig.showProgress);
    SetupStore("ShowChannelNr",  EPGSearchConfig.showChannelNr);
    SetupStore("OnePressTimerCreation",  EPGSearchConfig.onePressTimerCreation);
    
    SetupStore("UserMode1UseIt",  EPGSearchConfig.ShowModes[showUserMode1].GetUsage());
    SetupStore("UserMode1Description",  EPGSearchConfig.ShowModes[showUserMode1].GetDescription());
    SetupStore("UserMode1Time",  EPGSearchConfig.ShowModes[showUserMode1].GetTime());
    
    SetupStore("UserMode2UseIt",  EPGSearchConfig.ShowModes[showUserMode2].GetUsage());
    SetupStore("UserMode2Description",  EPGSearchConfig.ShowModes[showUserMode2].GetDescription());
    SetupStore("UserMode2Time",  EPGSearchConfig.ShowModes[showUserMode2].GetTime());
  
    SetupStore("UserMode3UseIt",  EPGSearchConfig.ShowModes[showUserMode3].GetUsage());
    SetupStore("UserMode3Description",  EPGSearchConfig.ShowModes[showUserMode3].GetDescription());
    SetupStore("UserMode3Time",  EPGSearchConfig.ShowModes[showUserMode3].GetTime());
    
    SetupStore("UserMode4UseIt",  EPGSearchConfig.ShowModes[showUserMode4].GetUsage());
    SetupStore("UserMode4Description",  EPGSearchConfig.ShowModes[showUserMode4].GetDescription());
    SetupStore("UserMode4Time",  EPGSearchConfig.ShowModes[showUserMode4].GetTime());

    SetupStore("UseSearchTimers",  EPGSearchConfig.useSearchTimers);
    SetupStore("UpdateIntervall",  EPGSearchConfig.UpdateIntervall);
    SetupStore("SVDRPPort",  EPGSearchConfig.SVDRPPort);
    SetupStore("CheckTimerConflicts",  EPGSearchConfig.checkTimerConflicts);

    SetupStore("TimeIntervallFRFF",  EPGSearchConfig.timeShiftValue);
    SetupStore("ToggleGreenYellow",  EPGSearchConfig.toggleGreenYellow);

    SetupStore("ShowRadioChannels", EPGSearchConfig.showRadioChannels);

    SetupStore("DefPriority",  EPGSearchConfig.DefPriority);
    SetupStore("DefLifetime",  EPGSearchConfig.DefLifetime);
    SetupStore("DefMarginStart",  EPGSearchConfig.DefMarginStart);
    SetupStore("DefMarginStop",  EPGSearchConfig.DefMarginStop);

    SetupStore("IgnorePayTV",  EPGSearchConfig.ignorePayTV);
    SetupStore("DefRecordingDir",  EPGSearchConfig.defrecdir);
    SetupStore("UseVDRTimerEditMenu",  EPGSearchConfig.useVDRTimerEditMenu);
    SetupStore("ShowChannelGroups",  EPGSearchConfig.showChannelGroups);
    SetupStore("ShowDaySeparators",  EPGSearchConfig.showDaySeparators);
    SetupStore("ShowEmptyChannels",  EPGSearchConfig.showEmptyChannels);

    SetupStore("DefSearchTemplateID",  EPGSearchConfig.DefSearchTemplateID);

    SetupStore("AddSubtitleToTimerMode",  EPGSearchConfig.addSubtitleToTimer);
    SetupStore("SetupMode",  EPGSearchConfig.SetupMode);

    cTemplFile::Reset();
    char* templateFilename = strdup(AddDirectory(CONFIGDIR, "epgsearchmenu.conf"));
    if (access(templateFilename, F_OK) == 0)
    {
	cTemplFile templFile;
	if (!templFile.Load(templateFilename))
	    esyslog("EPGSearch: could not load %s", templateFilename);
    }
    cTemplFile::PrepareDefaultTemplates();
    free(templateFilename);

    if (bRestart)
	cSearchTimerThread::Init();
}

void cMenuEPGSearchSetup::SetHelpKeys()
{
    const char* ItemText = Get(Current())->Text();
    if (!HasSubMenu())
    {
	if (strstr(ItemText, tr("Channel groups")) == ItemText)
	    SetHelp(REDBUTTON, NULL, NULL, tr("Button$Setup"));
	else if (strstr(ItemText, tr("Blacklists")) == ItemText)
	    SetHelp(REDBUTTON, NULL, NULL, tr("Button$Setup"));
	else if (strstr(ItemText, IndentMenuItem(tr("Search templates"))) == ItemText)
	    SetHelp(REDBUTTON, NULL, NULL, tr("Button$Setup"));
	else if (strstr(ItemText, tr("Default recording dir")) == ItemText)
	{
	    if (!InEditMode(ItemText, tr("Default recording dir"), data.defrecdir))
		SetHelp(REDBUTTON, NULL, NULL, tr("Button$Select"));
	}
	else if (strstr(ItemText, IndentMenuItem(tr("Main menu entry"))) == ItemText)
	{
	    if (!InEditMode(ItemText,  IndentMenuItem(tr("Main menu entry")), data.mainmenuentry))
		SetHelp(REDBUTTON, NULL, NULL, NULL);
	}
	else if (strstr(ItemText, IndentMenuItem(tr("Description"))) == ItemText)
	{
	    if (!InEditMode(ItemText, IndentMenuItem(tr("Description")), data.ShowModes[showUserMode1].szDescription) && 
		!InEditMode(ItemText, IndentMenuItem(tr("Description")), data.ShowModes[showUserMode2].szDescription) && 
		!InEditMode(ItemText, IndentMenuItem(tr("Description")), data.ShowModes[showUserMode3].szDescription) &&
		!InEditMode(ItemText, IndentMenuItem(tr("Description")), data.ShowModes[showUserMode4].szDescription))
		SetHelp(REDBUTTON, NULL, NULL, NULL);
	}
	else
	    SetHelp(REDBUTTON, NULL, NULL, NULL);
    }
}

eOSState cMenuEPGSearchSetup::ProcessKey(eKeys Key)
{
    int iTemp_hidemenu = data.hidemenu;
    int iTemp_useUserTime1 = data.ShowModes[showUserMode1].GetUsage();
    int iTemp_useUserTime2 = data.ShowModes[showUserMode2].GetUsage();
    int iTemp_useUserTime3 = data.ShowModes[showUserMode3].GetUsage();
    int iTemp_useUserTime4 = data.ShowModes[showUserMode4].GetUsage();
    int iTemp_showProgress = data.showProgress;
    int iTemp_useSearchTimers = data.useSearchTimers;

    eOSState state = cMenuSetupPage::ProcessKey(Key);

    const char* ItemText = Get(Current())->Text();
    int iOnChannelGroups = 0;
    int iOnDefRecDir = 0;
    int iOnSearchTemplates = 0;
    int iOnBlacklists = 0;
    if (!HasSubMenu())
    {
	if (strstr(ItemText, tr("Channel groups")) == ItemText)
	    iOnChannelGroups = 1;
	if (strstr(ItemText, tr("Blacklists")) == ItemText)
	    iOnBlacklists = 1;
	else if (strstr(ItemText, IndentMenuItem(tr("Search templates"))) == ItemText)
	    iOnSearchTemplates = 1;
	else if (strstr(ItemText, tr("Default recording dir")) == ItemText)
	    iOnDefRecDir = 1;
    }
    SetHelpKeys();

    if (iTemp_hidemenu != data.hidemenu ||
	iTemp_useUserTime1 != data.ShowModes[showUserMode1].GetUsage() ||
	iTemp_useUserTime2 != data.ShowModes[showUserMode2].GetUsage() ||
	iTemp_useUserTime3 != data.ShowModes[showUserMode3].GetUsage() ||
	iTemp_useUserTime4 != data.ShowModes[showUserMode4].GetUsage() ||
	iTemp_showProgress != data.showProgress ||
	iTemp_useSearchTimers != data.useSearchTimers)
    {
	Set();
	Display();
    }

    if (state == osUnknown) {
	switch (Key) {
	  case kBlue:
	      if (!HasSubMenu())
	      {
		  if (iOnChannelGroups == 1)
		      state = AddSubMenu(new cMenuChannelGroups);
		  if (iOnBlacklists == 1)
		      state = AddSubMenu(new cMenuBlacklists);
		  if (iOnDefRecDir == 1)
		      state = AddSubMenu(new cMenuDirSelect(data.defrecdir));
		  if (iOnSearchTemplates == 1)
		      state = AddSubMenu(new cMenuEPGSearchTemplate(NULL, NULL, false));
	      }
	      break;
	    case kRed:
		if (!HasSubMenu())
		{
		    data.SetupMode = 1 - data.SetupMode;
		    Set();
		    Display();
		    SetHelpKeys();
		    state = osContinue;
		}
		break;
	  default: break;
      }
  }
    return state;
}
