{% import '_facts_sorter.html' as facts_sorter %}
{% macro status_counts(caller, status, node_name, events, current_env, unreported_time=False, report_hash=False) -%}
  <a class="ui {{status}} label status" href="{{url_for('report', env=current_env, node_name=node_name, report_id=report_hash)}}">{{ status|upper }}</a>
  {% if status == 'unreported' %}
    <span class="ui label status"> {{ unreported_time|upper }} </span>
  {% else %}
    {% if events['failures'] %}<span class="ui small count label failed" title="events failure">{{events['failures']}}</span>{% else %}<span class="ui small count label">0</span>{% endif%}
    {% if events['successes'] %}<span class="ui small count label changed" title="events success">{{events['successes']}}</span>{% else %}<span class="ui small count label">0</span>{% endif%}
    {% if events['skips'] %}<span class="ui small count label skipped" title="resources skipped">{{events['skips']}}</span>{% else %}<span class="ui small count label">0</span>{% endif%}
    {% if events['noops'] %}<span class="ui small count label noop" title="events noop">{{events['noops']}}</span>{% else %}<span class="ui small count label">0</span>{% endif%}
  {% endif %}
{%- endmacro %}

{% macro event_status_counts(caller, status, count) -%}
  {% if count == 0 %}
    <span class="ui small count label">0</span>
  {% elif status == 'failure' %}
    <span class="ui small count label failed" title="events failure">{{count}}</span>
  {% elif status == 'success' %}
    <span class="ui small count label changed" title="events success">{{count}}</span>
  {% elif status == 'skipped' %}
    <span class="ui small count label skipped" title="events skipped">{{count}}</span>
  {% elif status == 'noop' %}
    <span class="ui small count label noop" title="events noop">{{count}}</span>
  {% endif %}
{%- endmacro %}

{% macro report_status(caller, status, node_name, metrics, current_env, unreported_time=False, report_hash=False) -%}
  <a class="ui {{status}} label status" href="{{url_for('report', env=current_env, node_name=node_name, report_id=report_hash)}}">{{ status|upper }}</a>
  {% if status == 'unreported' %}
    <span class="ui label status"> {{ unreported_time|upper }} </span>
  {% else %}
    {% for metric in config.DISPLAYED_METRICS %}
      {% set path = metric.split('.') %}
      {% set title = ' '.join(path) %}
      {% if metrics[path[0]] and metrics[path[0]][path[1]] %}
      {% set value = metrics[path[0]][path[1]] %}
      {% if value != 0 and value|int != value %}
        {% set format_str = '%.2f' %}
      {% else %}
        {% set format_str = '%s' %}
      {% endif %}
        <span title="{{ title }}" class="ui small count label {{ title }}">{{ format_str|format(value) }}</span>
      {% else %}
        <span title="{{ title }}" class="ui small count label">0</span>
      {% endif%}
    {% endfor %}
  {% endif %}
{%- endmacro %}

{% macro datatable_init(table_html_id, ajax_url, data, default_length, length_selector, extra_options=None, fact=None) -%}

  // Init datatable
  $.fn.dataTable.ext.errMode = 'throw';

  {% if data %}
  var data = {{ data }};
  {% endif %}

  var table = $('#{{ table_html_id }}').DataTable({
    {% if table_html_id == 'query_table' -%}
    "buttons": [
      {
        extend: 'csv',
        filename: 'Puppetboard_query',
        text: 'Download as CSV',
      },
      {
        extend: 'excel',
        filename: 'Puppetboard_query',
        text: 'Download as XLSX',
      },
    ],
    {% endif %}
    {% if data -%}
    // Data provided directly
    "data": data,
    "columns": [
    ],
    {% else %}
    // Data loading URL
    "ajax": "{{ ajax_url }}",
    // Permit flow auto-readjust (responsive)
    "autoWidth": false,
    // Activate "processing" message
    "processing": true,
    // Activate Ajax mode
    "serverSide": true,
    // Responsive
    "responsive": true,
    // Defer rendering out of screen lines (JIT)
    "deferRender": true,
    // Paging options
    "lengthMenu": {{ length_selector }},
    "pageLength": {{ default_length }},
    // Search as regex (does not apply if serverSide)
    "search": {"regex": true},
    {% if table_html_id == 'facts_table' -%}
    "order": [[ 0, "asc" ]],
    {% else -%}
    // Default sort
    "order": [[ 0, "desc" ]],
    {% endif -%}
    // Rendering - add rendering options for columns
    "columnDefs": [
    {% if table_html_id == 'facts_table' -%}
    { "targets": "fact_value",
      "width": "65%",
      "data:": null,
      "render": function (data, type, full, meta) {
        data = JSON.parse(data)

        url = data[0]
        to_show = pretty_print(data[1])

        return `<a title="${data[1]}" href="${url}">${to_show}</a>`
      },
      {{ facts_sorter.get_facts_sorter_type(fact) }}
    },
    {% else -%}
    {
      "targets": -1,
      "data:": null,
      "render": function (data, type, full, meta) {
        shorta = data.toString().replace(/[{},]/g, "<br />");
        shortb = shorta.replace(/u'/g, " ");
        shortc = shortb.replace(/'/g, " ");
        return shortc;
      }
    },
    {% endif %}
    ],
    {% endif %}
    // Custom options
    {% if extra_options %}{% call extra_options() %}Callback to parent defined options{% endcall %}{% endif %}
  });

  {% if table_html_id == 'query_table' -%}
  table.buttons().container().appendTo( $('div.dataTables_length', table.table().container()) );
  {% endif %}

  table.on('error', function ( e, settings, json ) {
    table.clear().draw();
    $('#facts_table_processing').hide(); })


  table.on('draw.dt', function(){
    $('#{{ table_html_id }} [data-localise]').transformDatetime();
  });

  // Override Datatables search box events to delay Ajax call while writing
  var searchWait = 0;
  var searchWaitInterval;
  $('.dataTables_filter input')
  .unbind()
  .bind('input', function(e){
    var item = $(this);
    searchWait = 0;
    if(!searchWaitInterval) searchWaitInterval = setInterval(function(){
      if(searchWait>=3){
        clearInterval(searchWaitInterval);
        searchWaitInterval = '';
        searchTerm = $(item).val();
        table.search(searchTerm).draw();
        searchWait = 0;
      }
      searchWait++;
    },80);
  });
{%- endmacro %}

{% macro checkbox_toggle(name, value_current, value_checked, value_unchecked, label) -%}

<div id="{{ name }}_div" class="ui toggle {% if (value_current == value_checked) %}checked{% endif %} checkbox">
    <input type="checkbox" {% if (value_current == value_checked) %}checked=""{% endif %}>
    <label>{{ label }}</label>
</div>
<script>
$('#{{ name }}_div').checkbox(
    'setting', 'onChange', function() {
        const url = new URL(window.location.href);
        if (url.pathname.endsWith("/{{ value_unchecked }}")) {
            url.pathname = url.pathname.replaceAll(/\/{{ value_unchecked }}$/ig, '/{{ value_checked }}')
        } else if (url.pathname.endsWith("/{{ value_checked }}")) {
            url.pathname = url.pathname.replaceAll(/\/{{ value_checked }}$/ig, '/{{ value_unchecked }}')
        } else {
            url.pathname += '/{{ value_unchecked }}'
        }
        window.location.href = url.href
    }
);
</script>

{%- endmacro %}
