/*
 * autotimeredit: A plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id: menueditweekdays.c 1.7 2005/10/19 23:22:17 hflor Exp $
 */

#include "autotimeredit.h"
#include "menueditweekdays.h"
#include "vdrtools.h"
#include <vdr/timers.h>

// --- cMenuEditDateItem -----------------------------------------------------

static int ParseWeekDays(const char *s)
{
  time_t day;
#if VDRVERSNUM >= 10323
  int weekdays;
  return cTimer::ParseDay(s, day, weekdays) ? weekdays : 0;
#else
  return cTimer::ParseDay(s, &day);
#endif
}

int cMenuEditWeekDaysItem::days[] = { ParseWeekDays("M------"),
                                      ParseWeekDays("-T-----"),
                                      ParseWeekDays("--W----"),
                                      ParseWeekDays("---T---"),
                                      ParseWeekDays("----F--"),
                                      ParseWeekDays("-----S-"),
                                      ParseWeekDays("------S"),
                                      ParseWeekDays("MTWTF--"),
                                      ParseWeekDays("MTWTFS-"),
                                      ParseWeekDays("MTWTFSS"),
                                      ParseWeekDays("-----SS")};

int GetWDay(time_t t)
{
  struct tm tm_r;
  int weekday = localtime_r(&t, &tm_r)->tm_wday;
  return weekday == 0 ? 6 : weekday - 1; // we start with monday==0!
}

cMenuEditWeekDaysItem::cMenuEditWeekDaysItem(const char *Name, int *WeekDays)
:cMenuEditItem(Name)
{
  weekdays = WeekDays;
  dayindex = -1;
  if (weekdays)
    for (int i = 0; i < (int) (sizeof(days) / sizeof(days[0])); i++)
      if ((days[i] & 0x7f) == (*weekdays & 0x7f))
        dayindex = i;
  Set();
}

void cMenuEditWeekDaysItem::Set(void)
{
  if (weekdays && *weekdays) {
#if VDRVERSNUM >= 10503
    SetValue(cTimer::PrintDay(0, *weekdays, false));
#elif VDRVERSNUM >= 10323
    SetValue(cTimer::PrintDay(0, *weekdays));
#else
    SetValue(cTimer::PrintDay(*weekdays, 0));
#endif
    return;
  } else
    SetValue("-------");
}

eOSState cMenuEditWeekDaysItem::ProcessKey(eKeys Key)
{
  eOSState state = cMenuEditItem::ProcessKey(Key);
  if (state == osUnknown && weekdays) {
    if (NORMALKEY(Key) == kLeft) {
      if (dayindex <= 0)
        dayindex = (int) (sizeof(days) / sizeof(days[0]));
      *weekdays = days[--dayindex];
      state = osContinue;
    } else if (NORMALKEY(Key) == kRight) {
      dayindex++;
      if (dayindex >= (int) (sizeof(days) / sizeof(days[0])))
        dayindex = 0;
      *weekdays = days[dayindex];
      state = osContinue;
    } else if (k1 <= Key && Key <= k7) {
      *weekdays ^= (1 << (Key - k1));
      state = osContinue;
    }
    if (state == osContinue)
      Set();
  }
  return state;
}
