{#
# This file is part of Invenio.
# Copyright (C) 2012, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#}

{% macro render_search_pagination(pagination) %}{%- block render_search_pagination scoped -%}
  {%- set args = request.args.copy().to_dict() -%}
  {%- set form_args = request.form.copy().to_dict() -%}
  {%- if form_args|length() and 'filter' in form_args -%}
    {%- do form_args.pop('filter') -%}
    {%- do args.update(form_args) -%}
    {%- set hash_tag = '#'+request.form.get('filter','') -%}
  {%- else -%}
    {%- set hash_tag = '' -%}
  {%- endif -%}
  {%- if pagination.pages > 1 -%}
  <ul class="pagination">
    {%- block pagination_first scoped -%}
    <li{{ ' class="disabled"'|safe if not pagination.has_prev }}>
      {%- do args.update({'jrec': 1}) -%}
      <a title="first" href="{{ url_for('search.search', **args)+hash_tag }}">&laquo;</a>
    </li>
    {%- endblock -%}
    {%- block pagination_prev scoped -%}
    <li{{ ' class="disabled"'|safe if not pagination.has_prev }}>
      {%- set jrec = (pagination.page-1)*pagination.per_page if pagination.has_prev else 1 -%}
      {%- do args.update({'jrec': jrec}) -%}
      <a title="prev" href="{{ url_for('search.search', **args)+hash_tag }}">&lsaquo;</a>
    </li>
    {%- endblock -%}
    {%- block pagination_pages scoped -%}
    {%- for page in pagination.iter_pages() %}
      {%- if page -%}
      {%- block pagination_page scoped -%}
        <li{{ ' class="active"'|safe if page == pagination.page }}>
      {%- do args.update({'jrec': (page-1)*pagination.per_page+1}) -%}
        <a href="{{ url_for('search.search', **args)+hash_tag }}">{{ page }}</a>
      </li>
      {%- endblock -%}
      {%- else -%}
        {%- block pagination_dots scoped -%}
        <li class="disabled"><a href="{{ hash_tag|default('#', true) }}">...</a></li>
        {%- endblock -%}
      {%- endif -%}
    {%- endfor -%}
    {%- endblock -%}
    {%- block pagination_next scoped -%}
    <li{{ ' class="disabled"'|safe if not pagination.has_next }}>
      {%- set jrec = (pagination.page+1)*pagination.per_page if pagination.has_next else (pagination.pages-1)*pagination.per_page+1 -%}
      {%- do args.update({'jrec': jrec}) -%}
      <a href="{{ url_for('search.search', **args)+hash_tag }}">&rsaquo;</a>
    </li>
    {%- endblock -%}
    {%- block pagination_last scoped -%}
    <li{{ ' class="disabled"'|safe if not pagination.has_next }}>
      {%- do args.update({'jrec': (pagination.pages-1)*pagination.per_page+1}) -%}
      <a title="last" href="{{ url_for('search.search', **args)+hash_tag }}">&raquo;</a>
    </li>
    {%- endblock -%}
  </ul>
  {%- endif -%}
{% endblock %}{% endmacro %}

{% macro results_actions() %}{%- block results_actions scoped -%}
  <div class="form-group">
    <span class="btn-group" class="col-sm-4">
      <span class="btn btn-default" onclick="$('[name=recid]').prop('checked', function() {return !$(this).prop('checked')});"
            class="btn">
        <i class="glyphicon glyphicon-check"
           rel="tooltip"
           title="{{ _('Toggle all') }}"></i>
      </span>
    </span>
  </div>
{% endblock %}{% endmacro %}


{% macro render_search_results(records, collection, pagination, format_record) %}{%- block render_search_results scoped -%}
  <style>
    .pagination {
      margin: 0px;
      vertical-align: middle;
    }

    /* fix for text in dropdowns - not to be aligned to right */
    .form-group.pull-right {
      text-align: left;
    }
  </style>
      <form class="form-inline" name="" action="{{ url_for('search.dispatch') }}" method="post">
        {%- block search_results_header scoped %}
        {{ results_actions() }}
        {% block search_result_nb_recs scoped %}
        {%- if pagination %}
        <div class="form-group">
          <p class="help-block hidden-xs">
            {%- set r_from = (pagination.page-1)*pagination.per_page+1 -%}
            {%- set r_to = pagination.page*pagination.per_page -%}
            {%- set r_of = pagination.total_count -%}
            {%- set r_to = r_to if r_to < r_of else r_of -%}
            {{ _('Showing records %(x_from)d to %(x_to)d out of %(x_total)d results.', x_from=r_from, x_to=r_to, x_total=r_of) }}
          </p>
        </div>
        {% endif %}
        {% endblock search_result_nb_recs %}
        {% block search_result_settings scoped %}
        <div class="form-group pull-right">
          {%- set args = request.values.copy().to_dict() -%}
            {%- set form_args = request.form.copy().to_dict() -%}
            {%- if form_args|length() and 'filter' in form_args -%}
              {%- do form_args.pop('filter') -%}
              {%- do args.update(form_args) -%}
            {%- endif -%}
            {%- set new_args = args.copy() -%}
          {% block search_result_settings_sort scoped %}
          <div class="btn-group">
            {%- if 'sf' not in new_args -%}{%- do new_args.update({'sf': config.CFG_BIBSORT_DEFAULT_FIELD}) -%}{%- endif -%}

            {%- set current_sf = new_args.get('sf') -%}
            {%- set current_so = new_args.get('so', config.CFG_BIBSORT_DEFAULT_FIELD_ORDER)-%}
            {%- set so_alternative = 'd' if current_so == 'a' else 'a' -%}

            {%- set used_args = new_args.copy() -%}
            {%- do used_args.update({'so': so_alternative}) -%}
            <a class="btn btn-default" href="{{ url_for('search.search', **used_args) }}{{ '#'+request.form.get('filter','')|default('', true) }}" tooltip="{{_('Sort ascending') if so_alternative == 'a' else _('Sort descending')}}">
              <i class="fa fa-sort-alpha-{{'desc' if so_alternative == 'a' else 'asc'}}"></i>
            </a>
            <a class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#">
              <i class="fa fa-random"></i> {{ _('Sort by') }}
              <span class="caret"></span>
            </a>

            {%- do new_args.pop('sf', None) -%}
            {%- if 'so' not in new_args -%}{%- do new_args.update({'so': 'a'}) -%}{%- endif -%}
            <ul class="dropdown-menu">
            {%- for sort_method in collection.sort_methods -%}
              {%- set active = current_sf == sort_method.name -%}
              {%- set used_args = new_args.copy() -%}
              {%- do used_args.update({'sf': sort_method.name}) -%}
              <li{% if active %} class="active"{% endif %}>
                <a href="{{ url_for('search.search', **used_args) }}{{ '#'+request.form.get('filter','')|default('', true) }}"
                   class="{{ 'active' if active }}">{{ sort_method.get_name_ln(g.ln) }}
                </a>
              </li>
            {%- endfor -%}
            </ul>
          </div>
          {%- endblock search_result_settings_sort %}
          {%- block search_result_settings_display scoped %}
          <div class="btn-group">
            <a class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#">
              <i class="glyphicon glyphicon-th"></i> {{ _('Display') }}
              <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
            {%- for i in collection.formatoptions if i.content_type == 'text/html' and i.visibility == 1 -%}
              {%- set used_args = new_args and new_args.copy() or dict() -%}
              {%- do used_args.update({'of':i.code}) -%}
              <li><a
                 href="{{ url_for('search.search', **used_args) }}{{ '#'+request.form.get('filter','')|default('', true) }}"
                 class="{{ ' active' if active }}">
                <i class="pull-right icon {{ ' glyphicon glyphicon-ok' if of==i.code }}"></i>
                {{ i.names.get(g.ln, i.name) }}
              </a></li>
            {%- endfor -%}
            <!-- dropdown menu links -->
            </ul>
          </div>
          {%- endblock search_result_settings_display %}
        </div>
        {%- endblock search_result_settings %}

        <hr/>
        {%- endblock search_results_header %}
        {%- block search_results scoped -%}
        {%- for record in records -%}{% set recordloop = loop %}{%- block search_result scoped -%}
          {%- set recid = record['recid'] %}
          {%- if of[0] == 'h' -%}
            <div class="row">
              {%- block search_result_prefix scoped -%}
              <div class="col-sm-1 col-xs-1">
                <label class="checkbox">
                  <input name="recid" type="checkbox" value="{{ recid }}" />
                  <abbr class="unapi-id" title="{{ recid }}"></abbr>
                  {{ recordloop.index+(pagination.page-1)*rg }}
                </label>
              </div>
              {%- endblock search_result_prefix -%}
              {%- block search_result_record scoped -%}
              <div class="col-sm-11 col-xs-11">
                {{ format_record(record, of, ln=g.ln, qid=qid, extra_context=dict(collection=collection))|u|safe }}
                {{ '<hr/>'|safe if not recordloop.last }}
              </div>
              {%- endblock search_result_record -%}
            </div>
          {%- else -%}
          {%- block search_result_record_nohtml scoped %}
          {{ format_record(record, of, ln=g.ln, extra_context=dict(collection=collection)) }}
          {%- endblock search_result_record_nohtml %}
          {%- endif -%}
          {%- endblock search_result -%}
        {%- endfor -%}
        {%- endblock search_results -%}

        {%- block search_results_footer scoped %}
        <hr/>
        <div class="row clearfix">
          <div class="col-md-12">
            {{ results_actions() }}
            {%- block search_results_export scoped -%}
            <div class="form-group">
              <select name="of" class="col-md-2 form-control">
              {%- for i in export_formats -%}
                <option value="{{ i.code }}"{{ ' selected' if request.args.get('of','hb')==i.code }}>
                  {{ i.names.get(g.ln, i.name) }}
                </option>
              {%- endfor -%}
              </select>
            </div>
            <div class="form-group">
              <button name="action" value="export" class="btn btn-default">
                <i class="glyphicon glyphicon-download-alt"
                   rel="tooltip"
                   title="{{ _('Export') }}">
                </i>
                {{ _('Export') }}
              </button>
            </div>
            {%- endblock search_results_export -%}
            {%- block search_results_pagination scoped -%}
            <div class="form-group pull-right">
              {{ render_search_pagination(pagination) }}
            </div>
            {%- endblock search_results_pagination -%}
          </div>
        </div>
        {%- endblock search_results_footer %}
      </form>

  {% for category, msg in get_flashed_messages(with_categories=True, category_filter=['search-results-after']) %}
    {{ msg|safe }}
  {% endfor %}
{% endblock %}{% endmacro %}

{% if not request.is_xhr %}
{% extends 'search/searchbar_frame.html' %}
{% block body %}
{{ render_search_results(records, collection, pagination, format_record) }}
{% endblock %}
{% else %}
{{ render_search_results(records, collection, pagination, format_record) }}
{% endif %}
