<%pre>

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

using namespace vdrlive;

</%pre>
<%args>
  // input parameters
  std::string timerid;
  std::string action;
</%args>
<%session scope="global">
  bool logged_in(false);
  TimerConflictNotifier timerNotifier;
</%session>
<%include>page_init.eh</%include>
<%cpp>
  reply.setHeader (tnt::httpheader::cacheControl, "no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate", true);
  if (!logged_in && LiveSetup().UseAuth()) {
    cToSvConcat targetUrl = "/login.html?redirect=";
    targetUrl.appendUrlEscaped(request.getQuery());
    return reply.redirect(targetUrl.data());
  }

  pageTitle = trVDR("Timers");
  TimerConflicts timerConflicts;

  if ( !timerid.empty()  && !action.empty() ) {
    std::string tId = SortedTimers::DecodeDomId(timerid);
//    dsyslog("live: DEBUG: TIMER: tId = %s", tId.c_str());
    int timer_id;
    const char *remote;
    {
      LOCK_TIMERS_READ;
      const cTimer* timer = SortedTimers::GetByTimerId(tId, Timers);
      if (!timer)
        throw HtmlError( tr("Couldn't find timer. Maybe you mistyped your request?") );
      timer_id = timer->Id();
      remote   = timer->Remote();
    }
    if (action == "delete") {
      if (!cUser::CurrentUserHasRightTo(UR_DELTIMERS))
        throw HtmlError( tr("Sorry, no permission. Please contact your administrator!") );
//                        dsyslog("live: timers.ecpp timer->Id() %d", timer->Id());
//                        dsyslog("live: timers.ecpp timer->Remote() %s", timer->Remote());
      TimerManager().DelTimer(timer_id, remote);
      timerNotifier.SetTimerModification();
    }
    if (action == "toggle") {
      TimerManager().ToggleTimerActive(timer_id, remote);
      timerNotifier.SetTimerModification();
    }
</%cpp>
<!DOCTYPE html>
<html>
  <script>
    history.go(-1);
  </script>
</html>
<%cpp>
  } else {
  std::string previousDay = "";
</%cpp>
<& pageelems.doc_type &>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>VDR-Live - <$ pageTitle $></title>
    <& pageelems.stylesheets &>
    <& pageelems.ajax_js &>
    <& pageelems.create_html_js &>
  </head>
  <body onpagehide="saveScrollPosition('content')" onpageshow="restoreScrollPosition()">
    <& pageelems.logo &>
    <& menu active=("timers") component=("timers.event_actions")>
    <div id="content">
      <div class="spacebar"><# spacer with fade-out effect #></div>
<%cpp>
    #ifdef DEBUG_LOCK
      dsyslog("live: pages/timers.ecpp LOCK_TIMERS_READ");
    #endif
      {
      LOCK_TIMERS_READ;
      cSortedTimers sortedTimers(Timers);
      if (sortedTimers.Size() == 0) {
</%cpp>
        <$ tr("No timer defined") $>
%      } else {
      <table class="listing timers" cellspacing="0" cellpadding="0">
<%cpp>
        // check for remote timers:
        bool noRemoteTimers = true;
        for (int i = 0; noRemoteTimers && i < sortedTimers.Size(); i++) {
          noRemoteTimers &= sortedTimers[i]->Local();
        }
        // check for search timers or tvscraper autotimer:
        bool noSearchTimers = true;
        for (int i = 0; noSearchTimers && i < sortedTimers.Size(); i++) {
          std::string recID;
          std::string recName;
          const cTimer *timer = sortedTimers[i];
          noSearchTimers &= timer->Local() && SortedTimers::SearchTimerInfo(*timer, "s-id").empty() && SortedTimers::TvScraperTimerInfo(*timer, recID, recName).empty();
        }
        // output of the timer list:
        for (int i = 0; i < sortedTimers.Size(); i++) {
          const cTimer *timer = sortedTimers[i];
          cToSvConcat longDescription;
          cToSvConcat searchTimName;
          std::string searchTimId;
          std::string recID;
          std::string recName;

          longDescription << "<p>";
          AppendHtmlEscapedAndCorrectNonUTF8(longDescription, SortedTimers::GetTimerInfo(*timer), "</p><p>");
          longDescription << "</p>";
          if (timer->Event())
          {
            bool truncated = false;
            LOCK_SCHEDULES_READ;
            if (timer->Event()->Description() ) {
              longDescription << "<hr><p>";
              AppendHtmlEscapedAndCorrectNonUTF8(longDescription, StringWordTruncate(timer->Event()->Description(), LiveSetup().GetMaxTooltipChars(), truncated), "</p><p>");
              if (truncated) longDescription << " ...";
              longDescription << "</p>";
            }
          }
          AppendHtmlEscapedAndCorrectNonUTF8(searchTimName, SortedTimers::SearchTimerInfo(*timer, "searchtimer"));
          searchTimId = SortedTimers::SearchTimerInfo(*timer, "s-id");
          if (searchTimName.empty() && searchTimId.empty() ) AppendHtmlEscapedAndCorrectNonUTF8(searchTimName, SortedTimers::TvScraperTimerInfo(*timer, recID, recName));
          std::string currentDay = SortedTimers::GetTimerDays(timer);
          const cTimer *nextTimer =  NULL;
          if (i < (sortedTimers.Size() - 1)) nextTimer = sortedTimers[i + 1];
          bool bottom = false;
          if (i == sortedTimers.Size() - 1) bottom = true;
          else {
            std::string nextDay = SortedTimers::GetTimerDays(nextTimer);
            bottom = (currentDay != nextDay);
          }
          if (previousDay != currentDay) {
            if (!previousDay.empty()) {
</%cpp>
            <tr class="spacer">
              <td colspan="12"/>
            </tr>
<%cpp>
            }
            previousDay = currentDay;
</%cpp>
        <tr class="head">
          <td colspan="12">
            <div class="boxheader"><div class="caption"><$ currentDay $></div></div>
          </td>
        </tr>
        <tr class="description">
          <td class="leftcol">&nbsp;</td>
          <td><div class="withmargin"><$ trVDR("Channel") $></div></td>
          <td class="td-hidden-xs"><div class="withmargin hidden-xs"><$ trVDR("Start") $></div></td>
          <td class="td-hidden-xs"><div class="withmargin hidden-xs"><$ trVDR("Stop")  $></div></td>
          <td class="td-hidden-xs"><div class="withmargin hidden-xs"><$ tr("Duration") $></div></td>
          <td class="td-hidden-xs"><div class="withmargin hidden-xs"><$ trVDR("Priority") $></div></td>
          <td><div class="withmargin"><$ trVDR("File") $></div></td>
          <td class="td-hidden-xs<$ noRemoteTimers ? " notpresent" : " remotetimer" $>"><div class="xs-nomargin hidden-xs"><$ trVDR("Record on") $></div></td>
          <td class="<$ noSearchTimers ? "notpresent" : "searchtimer" $>"><div class="withmargin"><$ tr("Search timer") $></div></td>
          <td class="rightcol"><img class="action-rightcol" src="img/transparent.png" alt="" /></td>
        </tr>
<%cpp>
          }
          std::string timerStateClass = "inactive";
          std::string timerStateIcon = "transparent.png";
          std::string timerStateHint;
          if (timer->Recording()) {
            timerStateClass = "recording";
            timerStateIcon = "arrow_rec.png";
            timerStateHint = tr("Timer is recording");
          }
          else if (timer->Flags() & tfActive) {
            if (timerConflicts.HasConflict(timer->Id() )) {
              timerStateClass = "conflict";
              timerStateIcon = "timer_conflict.png";
              timerStateHint = tr("Timer has a conflict");
            }
            else {
              timerStateClass = "active";
              timerStateIcon = "arrow.png";
              timerStateHint = tr("Timer is active");
            }
          }
          cToSvConcat<0> timerFile;
          AppendHtmlEscapedAndCorrectNonUTF8(timerFile, timer->File());
</%cpp>
        <tr class="<$ timerStateClass $>">
          <td class="leftcol <? bottom ? "bottomrow" ?>"><div class="<$ timerStateClass == "conflict"?"state_conflict":"state"$>"><img class="icon" src="<$ LiveSetup().GetThemedLink("img", timerStateIcon) $>" <%cpp> if (!timerStateHint.empty()) { </%cpp><& tooltip.hint text=(timerStateHint) &> <%cpp> } </%cpp>/></div></td>
          <td class="<? bottom ? "bottomrow" ?>"><div class="withmargin">
             <table class="noborder"><tr><td class="noborder"><span class="display-xs nowrap" > <$ cToSvDateTime(tr("%I:%M %p"), timer->StartTime()) $> - <$ cToSvDateTime(tr("%I:%M %p"), timer->StopTime()) $></span></td></tr>
%            {
%              LOCK_CHANNELS_READ;
               <tr><td class="noborder"><a href="schedule.html?channel=<$ timer->Channel()->Number()$>" title="<$tr("Transponder")$>: <$*cSource::ToString(timer->Channel()->Source() )$>-<$cToSvConcat(timer->Channel()->Frequency())$>-<$timer->Channel()->Parameters()$>"><$ timer->Channel()->Name() $></a></td></tr>
%            }
             </table>
          </div></td>
%         cToSvConcat longDescriptionTitle;
%         if (!longDescription.empty()) longDescriptionTitle << "title=\"" << longDescription << "\"";
          <td class="<? bottom ? "bottomrow" ?> td-hidden-xs"><div class="hidden-xs withmargin nowrap" <$$longDescriptionTitle$> ><$ cToSvDateTime(tr("%I:%M %p"), timer->StartTime()) $>  </div></td>
          <td class="<? bottom ? "bottomrow" ?> td-hidden-xs"><div class="hidden-xs withmargin nowrap" <$$longDescriptionTitle$> ><$ cToSvDateTime(tr("%I:%M %p"), timer->StopTime()) $>  </div></td>
          <td class="<? bottom ? "bottomrow" ?> td-hidden-xs"><div class="hidden-xs withmargin nowrap" <$$longDescriptionTitle$> ><$ FormatDuration(tr("%d:%02d"), timer->StopTime() - timer->StartTime()) $></div></td>
          <td class="<? bottom ? "bottomrow" ?> td-hidden-xs"><div class="hidden-xs withmargin nowrap" <$$longDescriptionTitle$> ><$ timer->Priority() $></div></td>
          <td class="<? bottom ? "bottomrow" ?>"><div class="withmargin">
%         if(timer->Event()) {
%           LOCK_CHANNELS_READ;
%           LOCK_SCHEDULES_READ;
            <a <& tooltip.display domId=(EpgEvents::EncodeDomId(timer->Channel()->GetChannelID(), timer->Event()->EventID())) &>
            class="apopup" title="<$$longDescription$>">
            <$$ cToSvReplace(timerFile, "~", "~<wbr>") $></a>
%         } else {
            <$$ cToSvReplace(timerFile, "~", "~<wbr>") $>
%         }
            </div>
          </td>
          <td class="<? bottom ? "bottomrow" ?> <$ noRemoteTimers ? "notpresent" : "remotetimer" $> td-hidden-xs"><div class="xs-nomargin"><$ timer->Local()?trVDR(" "):timer->Remote() $></div></td>
          <td class="<$ noSearchTimers ? "notpresent" : "searchtimer" $><? bottom ? " bottomrow" ?>"><div class="withmargin">
%         if ( !timer->Local() || searchTimId.empty() ) {
<# not created by epgsearch, check tvscraper autotimer #>
            <$$ cToSvReplace(searchTimName, "~", "~<wbr>") $>
%           if (!recID.empty() ) {
              <a href="epginfo.html?epgid=<$ recID $>"> <$$ cToSvReplace(recName, "~", "~<wbr>") $></a>
%           }
%         } else {
            <a href="edit_searchtimer.html?searchtimerid=<$ searchTimId $>"><$$ cToSvReplace(searchTimName, "~", "~<wbr>") $></a>
%         }
          </div></td>
          <td class="rightcol <? bottom ? "bottomrow" ?>">
            <# use a flexbox to allow dynamic arrangement upon changing screen size #>
            <div class="event_actions">
%             constexpr auto fileNameBreaks = "~";
%             cToSvDateTime label(tr("%I:%M %p"), timer->StartTime());
%             label.append(tr(" - "));
%             AppendHtmlEscapedAndCorrectNonUTF8(label, timer->File() );
              <a class="action-rightcol" href="timers.html?timerid=<$ SortedTimers::EncodeDomId(SortedTimers::GetTimerId(*timer)) $>&action=toggle"><img class="icon" src="<$ LiveSetup().GetThemedLink("img", (timer->Flags() & tfActive) ? "active.png" : "inactive.png") $>" alt="" <& tooltip.hint label=(label) className=("click-action") breaksAtRight=(fileNameBreaks) text=(tr("Toggle timer (in)active")) &> /></a>
              <div class="action-rightcol"><& pageelems.edit_timer timerId=(SortedTimers::GetTimerId(*timer)) className="icon" label=(label) breaksAtRight=(fileNameBreaks) &></div>
              <a class="action-rightcol" href="timers.html?timerid=<$ SortedTimers::EncodeDomId(SortedTimers::GetTimerId(*timer)) $>&action=delete" onclick="return confirm('<$ label $>\\n\\n<$ tr("Delete this timer?") $>')"><img class="icon" src="<$ LiveSetup().GetThemedLink("img", "del.png") $>" alt="" <& tooltip.hint label=(label) className=("click-action") breaksAtRight=(fileNameBreaks) text=(tr("Delete timer")) &> /></a>
            </div>
          </td>
        </tr>
%       }
      </table>
%     }
%     }
      <div class="spacebar"><# spacer with fade-out effect #></div>
    </div>
  </body>
</html>
% }
<%include>page_exit.eh</%include>

<%def event_actions>
<a href="edit_timer.html"><$ tr("New timer") $></a>
% if ( LiveFeatures< features::epgsearch >().Recent() ) {
<span class="sep">|</span>
<a href="timerconflicts.html"><$ tr("Timer conflicts") $></a>
% }
</%def>
