<%pre>

#include <exception.h>
#include <setup.h>
#include <tools.h>
#include <users.h>

using namespace vdrlive;

</%pre>
<%args>
  int channel_number = 0;
  std::string param;
  std::string async;
</%args>
<%session scope="global">
bool logged_in(false);
</%session>
<%cpp>
  if (!logged_in && LiveSetup().UseAuth()) {
    cToSvConcat targetUrl = "/login.html?redirect=";
    targetUrl.appendUrlEscaped(request.getQuery());
    return reply.redirect(targetUrl.data());
  }
  if (!cUser::CurrentUserHasRightTo(UR_SWITCHCHNL))
    throw HtmlError( tr("Sorry, no permission. Please contact your administrator!") );

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

  if (ajaxReq) {
    reply.setContentType( "application/xml" );
  } else {
    referrer = request.getHeader("Referer:");
  }

// do work
  const char *error_message = "";
  int l_channel_number = -1;
  tChannelID channelID;
  {
    const cChannel* channel = nullptr;
    LOCK_CHANNELS_READ;
    if (qparam.has("channel_number") && channel_number > 0) {
      channel = Channels->GetByNumber(channel_number);
    } else {
      channel = Channels->GetByChannelID(tChannelID::FromString(param.c_str()));
    }
    if (channel) {
      l_channel_number = channel->Number();
      channelID = channel->GetChannelID();
    } else
      error_message = tr("Couldn't find channel or no channels available.");

    if (l_channel_number != -1) {
      if (!Channels->SwitchTo(l_channel_number)) error_message = tr("Couldn't switch to channel.");
    }
  }

// report result
  if (!ajaxReq) {
    if (!referrer.empty() && referrer.find("login") == std::string::npos) {
      return reply.redirect(referrer);
    }
</%cpp>
<b>Switch-Channel Request</b>
<hr/>
Channel: <$ param $>/<$ channelID $><$ cToSvConcat(" [", l_channel_number, "]") $><br/>
Result:  <$ *error_message?"error":"success" $><br/>
Error:   <$ error_message $>
<hr/>
<%cpp>
  }
  else {
</%cpp>
<& xmlresponse.ajax name=("switch_channel") pname=("channel") value=(channelID) result=(*error_message == 0) error=(error_message) &>
<%cpp>
  }
</%cpp>
