{% extends "admin/_base.html" %}

{% from "macros/box.html" import m_box %}

{% macro audit_pager() %}
  <ul class="pager">
    <li class="previous {%- if not top_date %} disabled{% endif %}">
      <a href="{{ url_for(request.endpoint, after=top_date|default, **url_params) }}">&larr; {{ _("Newer") }}</a>
    </li>

    <li class="next {%- if not lowest_date %} disabled{% endif %}">
      <a href="{{ url_for(request.endpoint, before=lowest_date|default, **url_params) }}">{{ _("Older") }} &rarr;</a>
    </li>
  </ul>
{% endmacro %}

{% block content %}
  {%- call m_box(title="Global audit") %}
    <form id="audit-filters" action="{{ url_for(request.endpoint) }}" method="GET"
          class="form-inline" role="form">

      <div>
        {%- if 'after' in request.args %}
          <input type="hidden" name="after" value="{{ request.args['after'] }}"/>
        {%- elif 'before' in request.args %}
          <input type="hidden" name="before" value="{{ request.args['before'] }}"/>
        {%- endif %}

        <div class="form-group date">
        <span id="date-chooser" class="input-group date" data-date-end-date="+1d">
          <input class="form-control" type="text" value="{% if current_date %}{{ current_date }}{%- endif %}"/>
            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
        </span>
        </div>

        <div class="form-group">
          <select class="form-control" name="types">
            <option value="">{{ _('All contents') }}</option>
            {%- for name, type in all_classes %}
              <option value="{{ type }}" {%- if type in filter_types %}selected{%- endif %}>{{ name }}</option>
            {%- endfor %}
          </select>
        </div>

        <div class="form-group">
          <input class="form-control" type="text" id="user-select" name="user"
                 value="{%- if filter_user %}{{ filter_user.id }}{%- endif %}"/>
        </div>
      </div>

      <div>{{ audit_pager() }}</div>
    </form>

    <div style="margin-bottom: 25px;">
      {%- for day, entries in entries %}
        <ul class="unstyled"><h2>{{ day.strftime('%d-%m-%Y') }}</h2>
          {%- for entry in entries %}
            <li>
              {{ entry.date.strftime('%H:%M:%S') }} {{ entry.render() }}
            </li>
          {%- endfor %}
        </ul>
      {%- endfor %}
    </div>

    <div>{{ audit_pager() }}</div>
  {%- endcall %}

  {%- deferJS %}
    <script type="text/javascript">
      require(
          ['Abilian', 'jquery'],
          function (Abilian, $) {

            function setupAudit() {
              var input = $('#audit-filters input[name="user"]'),
                  form = input.get(0).form,
                  params = {
                    minimumInputLength: 2,
                    ajax: {
                      url: "{{ url_for("admin.audit_search_users") }}",
                      dataType: 'json',
                      quietMillis: 100,
                      data: function (term, page) {
                        return {q: term};
                      },
                      results: function (data, page) {
                        return {
                          results: data.results,
                          more: false
                        };
                      }
                    },
                    allowClear: true,
                    placeholder:   {{ _('Select user')|tojson }}
                  };

              {%- if filter_user %}
                params['initSelection'] = function (el, callback) {
                  callback({
                    id: {{ filter_user.id|tojson }},
                    text: {{ '%s (%s)'|format(filter_user.name, filter_user.email)|tojson }}
                  });
                };
              {%- endif %}

              input.select2(params)
                  .on('change', function () {
                    form.submit();
                  });

              var dateInput = $('#date-chooser').datepicker();
              dateInput.on(
                  'changeDate',
                  function (e) {
                    $('input[name="after"]').remove();
                    var before_input = $('input[name="before"]');
                    if (before_input.length < 1) {
                      before_input = $('<input>')
                          .attr({
                            'type': 'text',
                            'name': 'before'
                          })
                          .appendTo(form);
                    }
                    var isoDate = e.date;
                    isoDate.setDate(isoDate.getDate() + 1);
                    isoDate = isoDate.toISOString();
                    isoDate = isoDate.substring(0, isoDate.length - 1); // kill unwanted ending 'Z'
                    before_input.val(isoDate);
                    form.submit();
                  });

              $('select[name="types"]').on('change', function () {
                form.submit();
              });
            }

            Abilian.fn.onAppInit(setupAudit);
          });
    </script>
  {%- enddeferJS %}

{% endblock %}
