[% PROCESS _header.tt %]
[% PROCESS _message.tt %]
[% USE date %]

  <div class="flexrow 2xl:justify-between h-full">
    [% PROCESS _infobox.tt %]

    <div class="card min-w-[420px] max-w-[800px] w-full overflow-x-auto">
      <div class="head justify-between">
        <a href="broadcast.cgi" class="button header-button rounded w-[70px]" title="Go back to broadcast list">
          <i class="uil uil-angle-double-left"></i>Back
        </a>
        <div>
          <h3>[% IF broadcast.id != "new" %]Edit[% ELSE%]Create[% END %] Broadcast</h3>
        </div>
        <div class="w-[70px]"></div>
      </div>

      <div class="body">
        <form action="broadcast.cgi" method="POST">
          <input type="submit" name="send" value="save" style="display:none"><!-- make enter submit the form -->
          <input type="hidden" name="action" value="save">
          <input type="hidden" name="id" value="[% broadcast.id %]">
          <input type="hidden" name="CSRFtoken" value="[% get_user_token(c) %]">
          <table class="cellspacing">
          [% IF broadcast.id == "new" %]
            <tr>
              <th>Clone From Template</th>
              <td>
                <select onchange="chooseTemplate(this.value)">
                  <option value="" selected hidden disabled>choose template</option>
                  [% FOREACH t = bc_templates %]
                    <option value="[% t.basefile | html %]">[% t.name | html %]</option>
                  [% END %]
                </select>
              </td>
            </tr>
          [% END %]
            <tr>
              <th class="align-top">Save as Template</th>
              <td class="whitespace-normal"><input type="checkbox" value="1" name="template" id="template"[% IF broadcast.template %] checked[% END %]> <label for="template">Templates will never be displayed but can be cloned.</label></td>
            </tr>
            <tr>
              <th>Name</th>
              <td><input type="text" value="[% broadcast.name | html %]" name="name" class="w-full"></td>
            </tr>
            <tr>
              <th>Hide Before</th>
              <td>
                <div class="flex flex-nowrap gap-1 w-fit">
                  <input type="text"
                    class="cal_popup_clear"
                    value="[% IF broadcast.hide_before %][% format_date(broadcast.hide_before_ts, '%Y-%m-%d %H:%M:00') %][% END %]"
                    id="start"
                    name="hide_before"
                    onkeyup="verify_time(this.id)"
                    onchange="verify_time(this.id)"
                  >
                  <div>
                    <i class="uil uil-schedule text-lg cal_icon cal_popup for_start clickable" title="pick date"></i>
                  </div>
                </div>
              </td>
            </tr>
            <tr>
              <th>Expire After</th>
              <td>
                <div class="flex flex-nowrap gap-1 w-fit">
                  <input type="text"
                    class="cal_popup_clear"
                    value="[% IF broadcast.expires %][% format_date(broadcast.expires_ts, '%Y-%m-%d %H:%M:00') %][% END %]"
                    id="end"
                    name="expires"
                    onkeyup="verify_time(this.id)"
                    onchange="verify_time(this.id)"
                  >
                  <div>
                    <i class="uil uil-schedule text-lg cal_icon cal_popup for_end clickable" title="pick date"></i>
                  </div>
                </div>

                </td>
            </tr>
            <tr>
              <th>Annotation</th>
              <td>
                <div class="flex flex-nowrap gap-x-1">
                  <input type="radio" name="annotation" value=""[% IF !broadcast.annotation %] checked[% END %]>None
                  <input type="radio" name="annotation" value="info"[% IF broadcast.annotation == "info" %] checked[% END %] class="ml-2"><i class="uil uil-info round gray" title="Info"></i>
                  <input type="radio" name="annotation" value="warning"[% IF broadcast.annotation == "warning" %] checked[% END %] class="ml-2"><i class="fa-solid fa-exclamation round small yellow" title="Warning"></i>
                </div>
              </td>
            </tr>
            [% IF broadcast.frontmatter.keys.size > 0 %]
            <tr class="frontmatter_edit">
              <th class="align-top">
                Variables
                <br>
                <input type="button" onclick="jQuery('TR.raw').css('display', ''); jQuery('TR.frontmatter_edit').css('display', 'none')"; return(false); value="raw edit">
              </th>
              <td class="relative">
                <table class="frontmatterlist w-full">
                  <tr style="display: none;" class="firstrow frontmatter_row">
                    <td style="width: 0;" align="right" nowrap><b></th>
                    <td style="width:auto; padding-left: 5px;"><input type="text" class="frontmatter" name="" value=""></td>
                  </tr>
                [% FOREACH f = broadcast.frontmatter.keys.sort %]
                <tr class="frontmatter_row" data-name="[% f | html %]">
                  <th class="whitespace-nowrap w-5">[% f | html %]</th>
                  <td class="pl-1 w-auto"><input type="text" class="frontmatter w-full" name="frontmatter.[% f | html %]" value="[% broadcast.frontmatter.$f | html %]"></td>
                </tr>
                [% END %]
                </table>
              </td>
            </tr>
            [% END %]
            <tr class="raw"[% IF broadcast.frontmatter.keys.size > 0 %] style="display: none;"[% END %]>
              <th class="align-top">
                Text <span class="required">*</span>
                [% IF broadcast.frontmatter.keys.size > 0 %]
                <br>
                <input type="button" onclick="jQuery('TR.raw').css('display', 'none'); jQuery('TR.frontmatter_edit').css('display', ''); updateVariables(); return(false);" value="edit variables">
                [% END %]
              </th>
              <td>
                <textarea name="text" cols=74 rows=14 class="w-full" required>[% broadcast.raw_text %]</textarea>
                <div>
                  <button onclick="toggleElement('help-text'); return false;">
                    Help
                  </button>
                </div>
                <div id="help-text" style="display: none" class="border my-2 mr-2">
                  <h4 class="pl-2">Help</h4>
                  <ul class="pl-6 pr-2 list-disc">
                    <li>HTML is allowed, ex: <b>&lt;b&gt;bold text&lt;/b&gt;</b></li>
                    <li>Icons: &lt;i class=&quot;uil uil-question&quot;&gt;&lt;\/i&gt;</li>
                    <li>Images: &lt;img src="../themes/{{theme}}/images/logo_thruk.png" width=16 height=16&gt;</li>
                    <li>Text macros: {{contact}}, {{contactemail}}, {{date}} and {{theme}}</li>
                    <li>Frontmatter variables:
              <pre>---
  variable: create variables first
  another: test
  ---
  then use later like: {{variable}} and {{another}}</pre>
                    </li>
                  </ul>
                </div>
              </td>
            </tr>
            <tr>
              <th>Contacts</th>
              <td>
                [% PROCESS _wizard_list.tt id="id_contacts_wzd" wzd_args="contacts,contacts,1" %]
                <input type="text"
                      name="contacts"
                      id="contacts"
                      class="w-full"
                      value="[% broadcast.contacts.join(', ') | html %]"
                      onfocus="this.click()"
                      onclick="ajax_search.init(this, 'contact', {url:'status.cgi?format=search&amp;type=contact', striped:false, autosubmit:false, list: '\\s*[,!\+]+\\s*', button_links:[{text: 'use list wizard', id:'id_contacts_wzd_btn', icon:'fa-wand-magic-sparkles' }]})"
                >
              </td>
            </tr>
            <tr>
              <th>Contactgroups</th>
              <td>
                [% PROCESS _wizard_list.tt id="id_contactgroups_wzd" wzd_args="contactgroups,contactgroups,1" %]
                <input type="text"
                      name="contactgroups"
                      id="contactgroups"
                      class="w-full"
                      value="[% broadcast.contactgroups.join(', ') | html %]"
                      onfocus="this.click()"
                      onclick="ajax_search.init(this, 'contactgroup', {url:'status.cgi?format=search&amp;type=contactgroup', striped:false, autosubmit:false, list: '\\s*[,!\+]+\\s*', button_links:[{text: 'use list wizard', id:'id_contactgroups_wzd_btn', icon:'fa-wand-magic-sparkles' }]})"
                >
              </td>
            </tr>
            <tr>
              <th>Panorama Dashboard</th>
              <td>
                  <input type="checkbox" value="1" name="panorama"[% IF broadcast.panorama %] checked[% END %]> Display on panorama dashboards.
              </td>
            </tr>
            <tr>
                <th class="align-top">Login Page</th>
                <td class="whitespace-normal">
                    <input type="checkbox" value="1" name="loginpage"[% IF broadcast.loginpage %] checked[% END %]> Display on login page for unauthenticated users.
                </td>
              </tr>
            <tr>
              <td colspan=2>
                <div class="flex justify-center">
                  <button class="green">
                    [% IF broadcast.id != "new" %]Save[% ELSE%]Create[% END %] Broadcast
                  </button>
                </div>
              </td>
            </tr>
          </table>
        </form>
      </div>
    </div>

    <div class="w-[350px] hidden xl:block"></div>
  </div>

<script>
<!--
  function update_broadcast_preview(frontmatter_first) {
    var val        = jQuery('TEXTAREA[name=text]').val();
    var annotation = jQuery('INPUT[name=annotation]:checked').val();
    var tmp        = extract_frontmatter(val);
    val = tmp[0];
    if(frontmatter_first) {
      // update macros
      var newVal = '---\n';
      jQuery('INPUT.frontmatter').each(function(i, e) {
        var name = e.name.replace(/^frontmatter\./, '');
        tmp[1][name] = e.value;
        newVal += name+': '+e.value+'\n';
      });
      // update text from new variables
      newVal += '---\n\n';
      newVal += val;
      jQuery('TEXTAREA[name=text]').val(newVal);
    } else {
      for(var key in tmp[1]) {
        jQuery('INPUT[name="frontmatter.'+key+'"]').val(tmp[1][key]);
      }
    }
    val            = replace_macros(val, tmp[1]);
    val            = replace_macros(val, [% json_encode(broadcast.macros) %]);
    if(annotation == "warning") {
      val = '<i class="fa-solid fa-exclamation round small yellow" title="Warning"><\/i>' + val;
    }
    if(annotation == "info") {
      val = '<i class="uil uil-info round gray" title="Info"><\/i>' + val;
    }
    if(val == "") {
      jQuery('.js-broadcast-panel DIV.broadcast').html('<span class="preview">Broadcast preview...</span>');
    } else {
      jQuery('.js-broadcast-panel DIV.broadcast').html(val);
    }
    jQuery('.js-broadcast-panel').addClass("clickable").draggable();
  }

  jQuery(document).ready(function() {
    jQuery('.js-broadcast-panel DIV.control').hide();
    jQuery('.js-broadcast-panel DIV.dismiss A').prop('onclick',null).off('click').on('click', function(e) { e.preventDefault(); alert("preview cannot be dismissed."); return false; })
    jQuery('TEXTAREA[name=text]').on('keyup', function() { update_broadcast_preview(); });
    jQuery('INPUT[name=annotation]').on('change', function() { update_broadcast_preview(); });
    jQuery('INPUT.frontmatter').on('keyup', function() { update_broadcast_preview(true); });
    update_broadcast_preview();
  });

  function extract_frontmatter(text) {
    var macros = {};
    var matches = text.split(/(?:^|\n)\-\-\-\s*\n/);
    if(matches[0] || !matches[1]) {
      return([text, macros]);
    }
    matches.shift();
    var frontmatter = matches.shift().split(/\n/);
    for(var x=0; x<frontmatter.length; x++) {
      var tmp = splitN(frontmatter[x], ":", 2);
      if(tmp) {
        if(tmp[1]) {
          tmp[1] = tmp[1].replace(/^\s+/, '');
          macros[tmp[0]] = tmp[1];
        }
      }
    }
    text = matches.join("---\n")
    return([text, macros]);
  }

  function updateVariables() {
    var val    = jQuery('TEXTAREA[name=text]').val();
    var macros = extract_frontmatter(val)[1];
    // remove exceeding variables
    jQuery("TR.frontmatter_row").each(function(i, e) {
      var name = e.dataset["name"];
      if(name != undefined && !macros.hasOwnProperty(name)) {
        jQuery(e).remove();
      }
      delete macros[name];
    });
    // add missing
    for(var key in macros) {
      // clone first row
      var first = jQuery("TABLE.frontmatterlist TR.firstrow")[0];
      var copy  = jQuery(first).clone().css({"display": ""}).data("name", key).attr("data-name", key).removeClass("firstrow");
      jQuery(copy).find("TD").first().find("B").text(key+":");
      jQuery(copy).find("INPUT").first().val(macros[key]).attr("name", "frontmatter."+key);
      jQuery('TABLE.frontmatterlist tr:last').after(copy);
    }
  }

  function chooseTemplate(val) {
    redirect_url("broadcast.cgi?action=clone&id="+encodeURIComponent(val));
  }

-->
</script>

[% PROCESS _footer.tt %]
