<%pre>

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

using namespace vdrlive;

</%pre>
<%args>
  // input parameters
</%args>
<%session scope="global">
bool logged_in(false);
</%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());
}
</%cpp>
<%cpp>
  pageTitle = tr("Timer conflicts");
  TimerConflicts timerConflicts;
</%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=("timersconflicts")>
    <div id="content">
      <div class="spacebar"><# spacer with fade-out effect #></div>
%      if (timerConflicts.size() == 0) {
        <$ tr("No timer conflicts") $>
%      } else {
      <table class="listing timerconflicts" cellspacing="0" cellpadding="0">
<%cpp>
        // similar to the timers, we only want to display the searchtimer column if
        // data is available; so check if a timer conflict refers to a search timer
        bool noSearchTimers = true;
        for (TimerConflicts::iterator conflict = timerConflicts.begin(); conflict != timerConflicts.end(); ++conflict) {
          const std::list< TimerInConflict >& conflTimers = conflict->ConflictingTimers();
          for (std::list< TimerInConflict >::const_iterator confltimer = conflTimers.begin(); confltimer != conflTimers.end(); ++confltimer) {
            for (std::list<int>::const_iterator timerIndex = confltimer->concurrentTimerIndices.begin(); timerIndex != confltimer->concurrentTimerIndices.end(); ++timerIndex) {
              {
                LOCK_TIMERS_READ;
                const cTimer* timer = Timers->GetById(*timerIndex, (confltimer->remote == "") ? NULL : confltimer->remote.c_str());
                if (!timer) continue;
                std::string recID;
                std::string recName;
                noSearchTimers &= timer->Local() && SortedTimers::SearchTimerInfo(*timer, "s-id").empty() && SortedTimers::TvScraperTimerInfo(*timer, recID, recName).empty();
              }
            }
          }
        }
        // populate conflicting timers
        for (TimerConflicts::iterator conflict = timerConflicts.begin(); conflict != timerConflicts.end(); ++conflict) {
          const std::list< TimerInConflict >& conflTimers = conflict->ConflictingTimers();
          for (std::list< TimerInConflict >::const_iterator confltimer = conflTimers.begin(); confltimer != conflTimers.end(); ++confltimer) {
</%cpp>
            <tr class="head">
              <td colspan="12">
                <div class="boxheader">
                  <div class="caption"><$ concat(cToSvDateTime(tr("%A, %x"), conflict->ConflictTime()), " ", cToSvDateTime(tr("%I:%M %p"), conflict->ConflictTime()), tr(" - "), cToSvInt(confltimer->percentage), "%") $></div>
                  <div class="caption"><$ tr("Server")$>: <$ (confltimer->remote == "" ) ? tr("local") : confltimer->remote $></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"><$ trVDR("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="<$ 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>
            for (std::list<int>::const_iterator timerIndex = confltimer->concurrentTimerIndices.begin(); timerIndex != confltimer->concurrentTimerIndices.end(); ++timerIndex) {
              bool timer_has_event;
              {
                LOCK_TIMERS_READ;
                const cTimer* timer = Timers->GetById(*timerIndex, (confltimer->remote == "") ? NULL : confltimer->remote.c_str());
                if (!timer) continue;
                timer_has_event = timer->Event();
              }
              if (!timer_has_event) {
                LOCK_TIMERS_WRITE;
                cTimer* timer = Timers->GetById(*timerIndex, (confltimer->remote == "") ? NULL : confltimer->remote.c_str());
                LOCK_SCHEDULES_READ;
                timer->SetEventFromSchedule(Schedules);
              }
              LOCK_TIMERS_READ;
              const cTimer* timer = Timers->GetById(*timerIndex, (confltimer->remote == "") ? NULL : confltimer->remote.c_str());
              if (!timer) continue;

              std::list< int >::const_iterator nexttimerIndex = timerIndex;
              ++nexttimerIndex;
              bool bottom = (nexttimerIndex == confltimer->concurrentTimerIndices.end());

              std::string timerStateImg = "transparent.png";
              std::string timerStateClass;
              std::string timerStateHint;
              if (timer->Id() == confltimer->timerIndex) {
                timerStateImg = "timer_conflict.png";
                timerStateClass = "conflict";
                timerStateHint = tr("Timer has a conflict");
              }
              else if (timer->Flags() & tfActive) {
                timerStateImg = "arrow.png";
                timerStateClass = "active";
                timerStateHint = tr("Timer is active");
              }

              cToSvConcat longDescription;
              cToSvConcat searchTimName;
              std::string searchTimId;
              std::string recID;
              std::string recName;
              std::string title;

              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>";
                }
                title = cSv(timer->Event()->Title());
              }
              AppendHtmlEscapedAndCorrectNonUTF8(searchTimName, SortedTimers::SearchTimerInfo(*timer, "searchtimer"));
              searchTimId = SortedTimers::SearchTimerInfo(*timer, "s-id");
              if (searchTimName.empty() && searchTimId.empty() ) AppendHtmlEscapedAndCorrectNonUTF8(searchTimName, SortedTimers::TvScraperTimerInfo(*timer, recID, recName));
              cToSvConcat timerFile;
              AppendHtmlEscapedAndCorrectNonUTF8(timerFile, timer->File());
</%cpp>
              <tr class="<$ timer->Recording() ? "recording" : ((timer->Flags() & tfActive) ? timerStateClass : "inactive") $>">
                <# class="state" -> normally invisible #>
                <td class="leftcol <? bottom ? "bottomrow" ?>"><div class="<$ timerStateClass == "conflict"?"state_conflict":"state"$>"><img src="<$ LiveSetup().GetThemedLink("img", timerStateImg) $>" alt="" <%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>
<%cpp>
                  {
                    LOCK_CHANNELS_READ;
</%cpp>
                     <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>
%                  }
                   <tr><td class="noborder" style="padding-top:2pt"><span class="display-xs" title ="<$ trVDR("Priority") $>"><$ timer->Priority() $> </span></td></tr>
                   </table>
                </div></td>
                <td class="<? bottom ? "bottomrow" ?> td-hidden-xs"><div class="hidden-xs withmargin nowrap" title="<$ trVDR("Start")$>"><$ cToSvDateTime(tr("%I:%M %p"), timer->StartTime()) $>  </div></td>
                <td class="<? bottom ? "bottomrow" ?> td-hidden-xs"><div class="hidden-xs withmargin nowrap" title="<$ trVDR("Stop")$>"><$ cToSvDateTime(tr("%I:%M %p"), timer->StopTime()) $>  </div></td>
                <td class="<? bottom ? "bottomrow" ?> td-hidden-xs"><div class="hidden-xs withmargin nowrap" title="<$ trVDR("Duration")$>"><$ FormatDuration(tr("%d:%02d"), timer->StopTime() - timer->StartTime()) $></div></td>
                <td class="<? bottom ? "bottomrow" ?> td-hidden-xs"><div class="hidden-xs withmargin" title="<$ trVDR("Priority") $>"><$ timer->Priority() $></div></td>
                <td class="<? bottom ? "bottomrow" ?>"><div class="withmargin">
<%cpp>
               if(timer->Event() ) {
                 LOCK_CHANNELS_READ;
                 LOCK_SCHEDULES_READ;
</%cpp>
                  <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="<$ 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(" - ")).append(timer->File());
%                   int xsVisibleIcons = 3;     // all except the edit-timer icon
                    <a class="action-rightcol" href="searchresults.html?searchplain=<$$ cToSvUrlEscaped(title) $>"><img class="icon" src="<$ LiveSetup().GetThemedLink("img", "search.png") $>" alt="" <& tooltip.hint label=(label) className=("click-action") breaksAtRight=(fileNameBreaks) text=(tr("Search for repeats")) &> /></a>
                    <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) iCounter=((uintptr_t)&xsVisibleIcons) &></div>
                    <a class="action-rightcol" href="timers.html?timerid=<$ SortedTimers::EncodeDomId(SortedTimers::GetTimerId(*timer)) $>&action=delete"><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 class="notpresent xs-visible-<$ xsVisibleIcons $> xs-columns-<$ (xsVisibleIcons  + 2) / 3 $>"></div>
                  </div>
                </td>
              </tr>
%            }
            <tr class="spacer">
              <td colspan="10"/>
            </tr>
<%cpp>
          }
        }
</%cpp>
      </table>
%      }
      <div class="spacebar"><# spacer with fade-out effect #></div>
    </div>
  </body>
</html>
<%include>page_exit.eh</%include>


