<%pre>

#include <tools.h>
#include <timers.h>
#include <setup.h>
#include <epg_events.h>
#include <timerconflict.h>
#include <livefeatures.h>
#include <epgsearch.h>
#include <users.h>

#include <vdr/timers.h>
#include <vdr/svdrp.h>

using namespace vdrlive;

</%pre>
<%args>
  // input parameters
  std::string timerid;
  std::string epgid;
  std::string async;
  // form parameters
  std::string channel_string = "";
  int active = 1;
  std::string title = "";
  std::string remoteServerName = "";
  std::string date = "";
  bool wday_mon = false;
  bool wday_tue = false;
  bool wday_wed = false;
  bool wday_thu = false;
  bool wday_fri = false;
  bool wday_sat = false;
  bool wday_sun = false;
  std::string start_s = "00:00";
  std::string stop_s = "00:00";
  std::string monitoring;
  int priority = 0;
  int lifetime = 0;
  std::string directory = "";
  int nav_back = 1;
</%args>
<%session scope="global">
bool logged_in(false);
std::string edit_timerreferer;
TimerConflictNotifier timerNotifier;
</%session>
<%include>page_init.eh</%include>
<%cpp>
  if (!logged_in && LiveSetup().UseAuth()) {
    cToSvConcat targetUrl = "/login.html?redirect=";
    targetUrl.appendUrlEscaped(request.getQuery());
    return reply.redirect(targetUrl.data());
  }

  if (!cUser::CurrentUserHasRightTo(UR_EDITTIMERS))
    throw HtmlError( tr("Sorry, no permission. Please contact your administrator!") );

  bool ajaxReq = !async.empty() && (parse_int<int>(async) != 0);

  std::string message;
  tChannelID channel = tChannelID::FromString(channel_string.c_str());

  std::string aux = "";
  int timerId = 0;
  std::string oldRemote;
  cSubstring aux_epgsearch;
  cSubstring aux_tvscraper;
  bool others_monitor = false;
  tEventID event_monitoring_id = 0;
  time_t event_monitoring_startTime = 0;
  time_t event_monitoring_endTime = 0;
  if (!timerid.empty() ) {
    std::string tId = SortedTimers::DecodeDomId(timerid);
//    dsyslog("live: DEBUG: TIMER: timerid = %s", timerid);
//    dsyslog("live: DEBUG: TIMER: tId = %s", tId.c_str());
    LOCK_TIMERS_READ;
    const cTimer* timer = SortedTimers::GetByTimerId(tId, Timers);
    if (!timer)
      throw HtmlError( tr("Couldn't find timer. Maybe you mistyped your request?") );
    timerId = timer->Id();
    oldRemote = cSv(timer->Remote());
    aux = timer->Aux()?timer->Aux():"";
    aux_epgsearch = substringInXmlTag(aux, "epgsearch");
    aux_tvscraper = substringInXmlTag(aux, "tvscraper");
    others_monitor = aux_tvscraper.found() || aux_epgsearch.substringInXmlTag(aux, "s-id").found();
    if (!others_monitor) {
      LOCK_SCHEDULES_READ;
      const cEvent *event_monitoring = timer->Event();
// Wenn ein Event in den Garbage-Collector kommt, wird beim nächsten Umlauf (einmal pro Sekunde) der Hauptschleife dem Timer ein neuer (oder kein) Event zugewiesen. Der alte Event bleibt mindestens 5 Sekunden im Garbage-Collector. Wenn also der Timer einen Pointer auf einen Event hat, dann darf der auch dereferenziert werden
      if (event_monitoring) {
        event_monitoring_id = event_monitoring->EventID();
        event_monitoring_startTime = event_monitoring->StartTime();
        event_monitoring_endTime = event_monitoring->EndTime();
      }
    }
  }

  if (!others_monitor && event_monitoring_id == 0 && !epgid.empty() ) {
    LOCK_SCHEDULES_READ;
    const cEvent *event_monitoring = EpgEvents::GetEventByEpgId(epgid, Schedules);
// if we have no event, we do not support monitoring (which event should we monitor?)
    if (event_monitoring) {
      event_monitoring_id = event_monitoring->EventID();
      event_monitoring_startTime = event_monitoring->StartTime();
      event_monitoring_endTime = event_monitoring->EndTime();
    }
  }

  if (request.getMethod() == "POST" && title.empty()) { ++nav_back; message = tr("Please set a title for the timer!"); }
  if (request.getMethod() == "POST" && !title.empty()) {

    uint flags = ( active ? tfActive : 0 ) | ( (monitoring == "vps") ? tfVps : 0 );
    std::string weekdays = std::string( wday_mon ? "M" : "-" ) + ( wday_tue ? "T" : "-" ) + ( wday_wed ? "W" : "-" )
                + ( wday_thu ? "T" : "-" ) + ( wday_fri ? "F" : "-" ) + ( wday_sat ? "S" : "-" )
                + ( wday_sun ? "S" : "-" );
    int start = timeStringToInt(start_s);
    int stop = timeStringToInt(stop_s);

    cToSvConcat builder;
    builder << flags << ":"
            << channel << ":";
    if (weekdays != "-------") {
      builder << weekdays;
      if (!date.empty() ) builder << "@";
    }
    builder << date << ":"
            << start << ":"
            << stop << ":"
            << priority << ":"
            << lifetime << ":";
    if (!directory.empty() ) builder.appendReplace(directory, ":", "|" ).concat('~');
    builder.appendReplace(title, ":", "|" ) << ":";

// add aux information for epgsearch
    if (others_monitor && monitoring != "none" && monitoring != "vps")
      monitoring = "none";  // tvscraper does the monitoring -> no epgsearch monitoring
    if (weekdays != "-------" && monitoring != "none" && monitoring != "vps")
      monitoring = "none";  // monitoring only supported for single shot timers
    if (event_monitoring_id != 0 && monitoring != "none" && monitoring != "vps") {
      if (!aux_epgsearch.found() ) monitoring = "none";
    }

    if (monitoring == "none" || monitoring == "vps") {
      if (aux_epgsearch.found() )
        aux_epgsearch.substringInXmlTag(aux, "update").replace(aux, "0");
    } else {
      if (event_monitoring_id != 0) {
// we remove the epgsearch tag, and replace it with a new one
        LOCK_CHANNELS_READ;
        const cChannel *channel_p = Channels->GetByChannelID(channel);
        if (channel_p) {
          cTimer newTimer;
          if (newTimer.Parse(builder.c_str() )) {
            if (aux_epgsearch.found() ) eraseXmlTag(aux, "epgsearch");
            cToSvConcat aux_epgs("<epgsearch><channel>", channel_p->Number(), " - ", channel_p->Name(), "</channel><update>0</update><eventid>", event_monitoring_id, "</eventid><bstart>", event_monitoring_startTime - newTimer.StartTime(), "</bstart><bstop>", newTimer.StopTime() - event_monitoring_endTime, "</bstop></epgsearch>");
            aux.append(aux_epgs);
            aux_epgsearch = substringInXmlTag(aux, "epgsearch");
          }
        }
      }
      if (aux_epgsearch.found() ) {
        if (monitoring == "event_id")
          aux_epgsearch.substringInXmlTag(aux, "update").replace(aux, "2");
        else if (monitoring == "event_time")
          aux_epgsearch.substringInXmlTag(aux, "update").replace(aux, "1");
      }
    }

    builder.appendReplace(aux, ":", "|" );
    // Use StringReplace here because if ':' are characters in the
    // title or aux string it breaks parsing of timer definition
    // in VDRs cTimer::Parse method.  The '|' will be replaced
    // back to ':' by the cTimer::Parse() method.
    TimerManager().UpdateTimer(timerId, remoteServerName.c_str(), oldRemote.c_str(), channel, builder);
    timerNotifier.SetTimerModification();
</%cpp>
<!DOCTYPE html>
<html>
  <script>
    history.go(<$-nav_back-1$>);
  </script>
</html>
<%cpp>
//      return reply.redirect("html/back.html");
//      return reply.redirect(!edit_timerreferer.empty()?edit_timerreferer:"timers.html");
  } else {

  if (message.empty())
    edit_timerreferer = request.getHeader("Referer:", "timers.html");

{
  LOCK_TIMERS_READ;
  LOCK_CHANNELS_READ; // required for new cTimer( event )
  LOCK_SCHEDULES_READ;
  const cTimer* timer = nullptr;
  if (timerId != 0) {
    if (oldRemote.empty()) timer = Timers->GetById(timerId);
    else timer = Timers->GetById(timerId, oldRemote.c_str() );
  }

  std::unique_ptr<cTimer> eventTimer;
  if (!timer && !epgid.empty()) {
    const cEvent *event = EpgEvents::GetEventByEpgId(epgid, Schedules);
    if (event) {
      eventTimer.reset( new cTimer( event ) );
      timer = eventTimer.get();
    } else {
      esyslog("live: edit timer with epgid %s not valid", epgid.c_str() );
    }
  }
  if (!timer)
  {
    eventTimer.reset( new cTimer() );
    eventTimer->SetFlags( tfActive );
    timer = eventTimer.get();
  }

  if (timer && request.getMethod() == "GET" ) {
    active = timer->Flags() & tfActive;
    channel = timer->Channel()->GetChannelID();
    title = timer->File() ? timer->File() : "";
    remoteServerName = timer->Remote() ? timer->Remote() : "";
//  dsyslog("live: remoteServerName '%s'", remoteServerName.c_str());
    if (LiveFeatures<features::epgsearch>().Recent() ) {
      std::string::size_type tilde_found = title.rfind('~');
      if (tilde_found != std::string::npos) {
        directory = title.substr(0, tilde_found);
        title.erase(0, tilde_found+1);
      }
    }
    // TRANSLATORS: only adjust the ordering and separators, don't translate the m's, d's and y's
    date = timer->Day() ? DatePickerToC(timer->Day(), "yyyy-mm-dd") : "";
    wday_mon = timer->WeekDays() & 0x01;
    wday_tue = timer->WeekDays() & 0x02;
    wday_wed = timer->WeekDays() & 0x04;
    wday_thu = timer->WeekDays() & 0x08;
    wday_fri = timer->WeekDays() & 0x10;
    wday_sat = timer->WeekDays() & 0x20;
    wday_sun = timer->WeekDays() & 0x40;
    start_s = intToTimeString(timer->Start() );
    stop_s = intToTimeString(timer->Stop() );
    priority = timer->Priority();
    lifetime = timer->Lifetime();
// figure out monitoring of this timer
    if ( timer->Flags() & tfVps ) {
      monitoring = "vps";
    } else {
      if (others_monitor | !aux_epgsearch.found() || !LiveFeatures<features::epgsearch>().Recent() ) {
        monitoring = "none";
      } else {
// we have epgsearch, and this timer was not created by tvscraper
        cSv update = aux_epgsearch.substringInXmlTag(aux, "update").substr(aux);
        if (update == "2") {
          monitoring = "event_id";
        } else if (update == "1") {
          monitoring = "event_time";
        } else {
          monitoring = "none";
        }
      }
    }
  }
}
</%cpp>
<& pageelems.doc_type &>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>VDR Live - <$ timerid.empty() ? tr("New timer") : tr("Edit timer")  $></title>
<%cpp>
  if (!ajaxReq) {
</%cpp>
    <& pageelems.stylesheets &>
    <& pageelems.ajax_js &>
<%cpp>
  }
</%cpp>
    <script type="text/javascript"><!--
    function initform()
    {
      changedwday()
    }

    function changedwday()
    {
      <# some elements to be changed by the function can be missing #>
      if (
        document.getElementById("wday_mon").checked ||
        document.getElementById("wday_tue").checked ||
        document.getElementById("wday_wed").checked ||
        document.getElementById("wday_thu").checked ||
        document.getElementById("wday_fri").checked ||
        document.getElementById("wday_sat").checked ||
        document.getElementById("wday_sun").checked) {
          var element = document.getElementById("monitoring_option_id")
          if (element !== null) element.style.display = "none"
          element = document.getElementById("monitoring_option_time")
          if (element !== null) element.style.display = "none"
          if (!document.getElementById("monitoring_vps").checked) {
            document.getElementById("monitoring_none").checked = 1
            element = document.getElementById("monitoring_event_id")
            if (element !== null) element.checked = 0
            element = document.getElementById("monitoring_event_time")
            if (element !== null) element.checked = 0
            }
        } else {
          var element = document.getElementById("monitoring_option_id")
          if (element !== null) element.style.display = "revert-layer"
          element = document.getElementById("monitoring_option_time")
          if (element !== null) element.style.display = "revert-layer"
        }
    }
    //--></script>

  </head>
  <body onload="initform()" onpagehide="saveScrollPosition('content')" onpageshow="restoreScrollPosition()">
<%cpp>
  if (!ajaxReq) {
</%cpp>
    <& pageelems.logo &>
    <& menu active=("timers") &>
<%cpp>
  }
</%cpp>
    <div id="content">
      <div class="spacebar"><# spacer with fade-out effect #></div>
      <form method="post" name="edit_timer" id="<$ timerid $>" action="edit_timer.ecpp">
        <input type="hidden" name="timerid" value="<$ timerid $>"/>
        <input type="hidden" name="epgid" value="<$ epgid $>"/>
        <input type="hidden" name="nav_back" value="<$ nav_back $>"/>
        <table class="form" cellpadding="0" cellspacing="0">
          <tr class="head">
            <td class="toprow leftcol rightcol" colspan="2"><div class="boxheader"><div class="caption"><$ !timerid.empty() ? tr("Edit timer") : tr("New timer") $></div></div></td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ trVDR("Active") $>:</div></td>
            <td class="rightcol"><div class="options">
              <div class="dotted">
                <input id="active_1" name="active" value="1" <{ reply.out() << ( active ? "checked=\"checked\"" : "" ); }> type="radio"></input>
                <label for="active_1"><$ trVDR("yes") $></label>
              </div>
              <div class="dotted">
                <input id="active_0" name="active" value="0" <{ reply.out() << ( !active ? "checked=\"checked\"" : "" ); }> type="radio"></input>
                <label for="active_0"><$ trVDR("no") $></label>
              </div>
            </div></td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ trVDR("Channel") $>:</div></td>
            <td class="rightcol"><div><& channels_widget name=("channel_string") channelid=(true) selected=(channel) &></div></td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ tr("Title" ) $>:</div></td>
            <td class="rightcol"><input type="text" name="title" value="<$ title $>" size="55" class="width99" /></td>
          </tr>
<%cpp>
          cStringList svdrpServerNames;
          if (GetSVDRPServerNames(&svdrpServerNames)) {
            svdrpServerNames.Sort(true);
</%cpp>
          <tr>
            <td class="label leftcol"><div class="withmargin"><$ tr("Server" ) $>:</div></td>
            <td class="rightcol"><select name="remoteServerName" size="1" id="remoteServerName" style="margin-top: 5px">
              <option/>
<%cpp>
              for (int i = 0; i < svdrpServerNames.Size(); i++) {
              std::string rsrv = svdrpServerNames[i];
</%cpp>
              <option
%                if (rsrv == remoteServerName) {
                selected="selected"
%                }
              ><$ rsrv $></option>
<%cpp>
              }
</%cpp>
              </select>
            </td>
          </tr>
<%cpp>
          svdrpServerNames.Clear();
          }
</%cpp>
<%cpp>
          if ( LiveFeatures<features::epgsearch>().Recent() ) {
            RecordingDirs recordingdirs(true);
</%cpp>
          <tr>
            <td class="label leftcol"><div class="withmargin"><$ tr("Directory" ) $>:</div></td>
            <td class="rightcol"><select name="directory" size="1" id="directory">
                 <option></option>
%           for (RecordingDirs::iterator rdir = recordingdirs.begin(); rdir != recordingdirs.end(); ++rdir) {
              <option value="<$ *rdir $>"<?? directory == *rdir ? " selected=\"selected\"" ?>><$ *rdir $></option>
%            }
               </select>
            </td>
          </tr>
<%cpp>
          }
</%cpp>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ trVDR("Day") $>:</div></td>
            <td class="rightcol"><input id="date" name="date" type="date" value="<$ date $>" /></td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ tr("Weekday") $>:</div></td>
            <td class="rightcol"><div class="options">
              <div class="dotted">
                <input id="wday_mon" type="checkbox" name="wday_mon" value="1" <? wday_mon ? "checked=\"checked\"" ?> onclick="changedwday()" />
                <label for="wday_mon"><$ tr("Monday") $></label>
              </div>
              <div class="dotted">
                <input id="wday_tue" type="checkbox" name="wday_tue" value="1" <? wday_tue ? "checked=\"checked\"" ?> onclick="changedwday()" />
                <label for="wday_tue"><$ tr("Tuesday") $></label>
              </div>
              <div class="dotted">
                <input id="wday_wed" type="checkbox" name="wday_wed" value="1" <? wday_wed ? "checked=\"checked\"" ?> onclick="changedwday()" />
                <label for="wday_wed"><$ tr("Wednesday") $></label>
              </div>
              <div class="dotted">
                <input id="wday_thu" type="checkbox" name="wday_thu" value="1" <? wday_thu ? "checked=\"checked\"" ?> onclick="changedwday()" />
                <label for="wday_thu"><$ tr("Thursday") $></label>
              </div>
              <div class="dotted">
                <input id ="wday_fri" type="checkbox" name="wday_fri" value="1" <? wday_fri ? "checked=\"checked\"" ?> onclick="changedwday()" />
                <label for="wday_fri"><$ tr("Friday") $></label>
              </div>
              <div class="dotted">
                <input id="wday_sat" type="checkbox" name="wday_sat" value="1" <? wday_sat ? "checked=\"checked\"" ?> onclick="changedwday()" />
                <label for="wday_sat"><$ tr("Saturday") $></label>
              </div>
              <# add class "first" if weekdays shall start with sunday #>
              <div class="dotted">
                <input id="wday_sun" type="checkbox" name="wday_sun" value="1" <? wday_sun ? "checked=\"checked\"" ?> onclick="changedwday()" />
                <label for="wday_sun"><$ tr("Sunday") $></label>
              </div>
            </div></td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ trVDR("Start") $>:</div></td>
            <td class="rightcol"><input type="time" name="start_s" value="<$ start_s $>" /> </td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ trVDR("Stop") $>:</div></td>
            <td class="rightcol"><input type="time" name="stop_s" value="<$ stop_s $>" />
</td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ tr("Monitoring") $>:</div></td>
            <td class="rightcol"><div class="options">
              <div class="dotted">
                <input id="monitoring_none" name="monitoring" value="none" <? monitoring=="none" ? "checked=\"checked\"" ?> type="radio"></input>
                <label for="monitoring_none"><$ tr("none") $></label>
              </div>
              <div class="dotted">
                <input id="monitoring_vps" name="monitoring" value="vps" <? monitoring=="vps" ? "checked=\"checked\"" ?> type="radio"></input>
                <label for="monitoring_vps"><$ trVDR("VPS") $></label>
              </div>
%             if ( (!others_monitor && event_monitoring_id != 0 && LiveFeatures<features::epgsearch>().Recent()) || monitoring=="event_id" || monitoring=="event_time") {
              <# why are these options not included all the time? #>
              <div id="monitoring_option_id" class="dotted" style="display: none">
                <input id="monitoring_event_id" name="monitoring" value="event_id" <? monitoring=="event_id" ? "checked=\"checked\"" ?> type="radio"></input>
                <label for="monitoring_event_id"><$ tr("event ID") $></label>
              </div>
              <div id="monitoring_option_time" class="dotted" style="display: none">
                <input id="monitoring_event_time" name="monitoring" value="event_time" <? monitoring=="event_time" ? "checked=\"checked\"" ?> type="radio"></input>
                <label for="monitoring_event_time"><$ tr("event time") $></label>
              </div>
%             }
            </div></td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ trVDR("Priority") $>:</div></td>
            <td class="rightcol"><input type="number" size="6" min="0" max="99" name="priority" value="<$ priority $>" /></td>
          </tr>

          <tr>
            <td class="label leftcol"><div class="withmargin"><$ trVDR("Lifetime") $>:</div></td>
            <td class="rightcol"><input type="number" size="6" min="0" max="99" name="lifetime" value="<$ lifetime $>" /></td>
          </tr>

          <tr>
            <td class="buttonpanel leftcol rightcol bottomrow" colspan="2">
              <div class="withmargin">
              <button class="green" type="submit"><$ tr("Save") $></button>
              <button type="button" class="red" onclick="history.go(<$-nav_back$>)"><$ tr("Cancel") $></button>
              </div>
            </td>
          </tr>
        </table>
      </form>
      <div class="error">
        <$ message $>
      </div>
      <div class="spacebar"><# spacer with fade-out effect #></div>
    </div>
  </body>
</html>
% }
<%include>page_exit.eh</%include>
