{% extends './base.html'%}
{% load i18n bootstrap4 html navigation %}

{% block body_class %}samples{% endblock %}

{% block content %}{% newlineless %}{% spaceless %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{% url 'textrank:index' %}">TextRank</a></li>
        <li class="breadcrumb-item active" aria-current="page">{% trans 'Образцы' %}</li>
    </ol>
</nav>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
{% if instance %}
    <h1 class="h2">{% trans 'Образец' %} #{{ instance.id }}</h1>
{% else %}
    <h1 class="h2">{% trans 'Образцы' %}</h1>
{% endif %}
    <div class="btn-toolbar mb-2 mb-md-0">
    {% if instance %}
        <div class="btn-group">
            <a href="{% url 'textrank:samples' %}" class="btn btn-sm btn-outline-secondary">
                <span class="ml-1">{% trans 'Список образцов' %}</span>
            </a>
        </div>
    {% else %}
        {% url 'textrank:samples' as path %}
        <div class="btn-group mr-2">{% include './_search_form.html' %}</div>
        <div class="btn-group">
            <a href="#form" class="btn btn-sm btn-outline-secondary">
                <span class="fa fa-plus"></span>
                <span class="ml-1">{% trans 'добавить' %}</span>
            </a>
        </div>
        <div class="dropdown">
            <button type="button" id="dropdownMenuOrdering" data-toggle="dropdown" \
                aria-haspopup="true" aria-expanded="false" \
                class="btn btn-sm btn-outline-secondary ml-2 dropdown-toggle \
                {% if orders %}active{% endif %}">
                <span class="fa fa-sort"></span>
                <span class="ml-1">{% trans 'сортировка' %}</span>
            </button>
            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuOrdering">
                <a href="{{ path }}{% delparams request 'o' %}" \
                    class="dropdown-item {% if not orders %}active{% endif %}"> \
                    -updated \
                </a>
                <a href="{{ path }}{% addparams request o='updated' %}" \
                    class="dropdown-item {% if orders_string == 'updated' %}active{% endif %}"> \
                    updated \
                </a>
                <a href="{{ path }}{% addparams request o='message' %}" \
                    class="dropdown-item {% if orders_string == 'message' %}active{% endif %}"> \
                    message \
                </a>
                <a href="{{ path }}{% addparams request o='-message' %}" \
                    class="dropdown-item {% if orders_string == '-message' %}active{% endif %}"> \
                    -message \
                </a>
                <a href="{{ path }}{% addparams request o='created' %}" \
                    class="dropdown-item {% if orders_string == 'created' %}active{% endif %}"> \
                    created \
                </a>
                <a href="{{ path }}{% addparams request o='-created' %}" \
                    class="dropdown-item {% if orders_string == '-created' %}active{% endif %}"> \
                    -created \
                </a>
                <a href="{{ path }}{% addparams request o='last_editor__username' %}" \
                    class="dropdown-item {% if orders_string == 'last_editor__username' %}active{% endif %}"> \
                    last_editor__username \
                </a>
                <a href="{{ path }}{% addparams request o='-last_editor__username' %}" \
                    class="dropdown-item {% if orders_string == '-last_editor__username' %}active{% endif %}"> \
                    -last_editor__username \
                </a>
                <a href="{{ path }}{% addparams request o='id' %}" \
                    class="dropdown-item {% if orders_string == 'id' %}active{% endif %}"> \
                    id \
                </a>
                <a href="{{ path }}{% addparams request o='-id' %}" \
                    class="dropdown-item {% if orders_string == '-id' %}active{% endif %}"> \
                    -id \
                </a>
            </div>
        </div>
        <div class="dropdown mr-0">
            <button type="button" id="dropdownMenuGroup" data-toggle="dropdown" \
                aria-haspopup="true" aria-expanded="false" \
                class="btn btn-sm btn-outline-secondary ml-2 dropdown-toggle \
                {% if filters.group is not None %}active{% endif %}">
                <span class="fa fa-filter"></span>
                <span class="ml-1">{% trans 'группа' %}</span>
            </button>
            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuGroup">
                <a href="{{ path }}{% delparams request 'group' %}" class="dropdown-item {% if filters.group is None %}active{% endif %}">{% trans 'Любая' %}</a>
            {% for group in groups %}
                <a href="{{ path }}{% addparams request group=group.id %}" class="dropdown-item {% if filters.group == group.id|stringformat:'d' %}active{% endif %}">{{ group.name }}</a>
            {% endfor %}
            </div>
        </div>
    {% endif %}
    </div>
</div>

{% if not instance %}
<div class="table-responsive">
    <table class="table table-striped table-sm mb-3">
        <thead class="bg-dark text-white">
            <tr>
                <th>{% trans 'Образец' %}</th>
                <th>{% trans 'Группа' %}</th>
                <th>{% trans 'Создан' %}</th>
                <th>{% trans 'Обновлён' %}</th>
                <th>{% trans 'Редактор' %}</th>
                <th>ID</th>
            </tr>
        </thead>
        <tbody>
        {% url 'textrank:samples' as samples_url %}
        {% for sample in page.object_list %}
            <tr>
                <td>
                    <a class="text-body" href="{% url 'textrank:sample' id=sample.id %}">{{ sample.message|truncatewords:10 }}</a>
                </td>
                <td>
                    <small class="text-monospace">
                        <a href="{{ samples_url }}?group={{ sample.group_id }}" class="text-body">{{ sample.group }}</a>
                    </small>
                </td>
                <td class="text-nowrap isoformat">{{ sample.created.isoformat }}</td>
                <td class="text-nowrap isoformat">{{ sample.updated.isoformat }}</td>
                <td>{{ sample.last_editor|default:'---' }}</td>
                <td>{{ sample.id }}</td>
            </tr>
        {% empty %}
            <tr>
                <td colspan="8">{% trans 'Не найдено ни одной записи.' %}</td>
            </tr>
        {% endfor %}
        </tbody>
    {% if page.object_list %}
        <tfoot>
            <tr>
                <td colspan="8" class="pr-0">{% include './_table_pagination.html' %}</td>
            </tr>
        </tfoot>
    {% endif %}
    </table>
</div>
<h2 class="h3">{% trans 'Добавить новый образец' %}</h2>
{% endif %}

<div class="row">
    <div class="col-md-8">
        <form id="form" class="form bg-light p-2 mb-4" role="form" method="post" enctype="multipart/form-data">
            <input type="hidden" name="next" value="{{ next|escape }}" />
            {% csrf_token %}
            {{ form.non_field_errors }}
            {% for hidden in form.hidden_fields %}{{ hidden }}{% endfor %}
            {{ form.group|form_group }}
            {{ form.message|form_group }}
            <div class="d-flex justify-content-between">
                <button type="submit" class="btn btn-dark">
                    <i class="fa fa-save" aria-hidden="true"></i> \
                    {% trans 'Сохранить' %} \
                </button>
            {% if instance %}
                <button type="button" class="btn btn-danger sample-delete">
                    <i class="fa fa-remove" aria-hidden="true"></i> \
                    {% trans 'Удалить' %} \
                </button>
            {% endif %}
                <button type="button" class="btn btn-secondary sample-test">
                    <i class="fa fa-search" aria-hidden="true"></i> \
                    {% trans 'Протестировать' %} \
                </button>
            </div>
        </form>
    </div>
    <div class="col-md-4">
        <pre id="result" class="bg-light mb-4" style="height:440px; overflow:auto"></pre>
    </div>
</div>
{% endspaceless %}{% endnewlineless %}{% endblock %}

{% block javascript_page %}{% newlineless_javascript %}
<script type="text/javascript">
// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    }
});
</script>
<script type="text/javascript">
var _question = "{% trans 'Вы уверены?' %}";

$(document).ready(function($) {
    var language = $('html').attr('lang') || 'ru';
    moment.updateLocale(language, {});
    // Перерисовываем ISO дату по локальному времени юзера.
    $('.isoformat').each(function(i, el) {
        var $el = $(el);
        $el.text(moment($el.text()).format('L LT'));
    });
    $('body')
        .on('click', '.sample-test', function(e) {
            e.preventDefault();
            var group_id = Number($('#id_group').val()),
                text = $('#id_message').val();
            if (!group_id || !text) {
                alert("{% trans 'Сначала заполните форму.' %}");
                return
            }
            $.ajax({
                method: 'post',
                url: "{% url 'textrank:rank' format='json' %}",
                data: {text: text, verbose: true},
            }).done(function(data) {
                $('#result').text(JSON.stringify(data, null, 2));
                var msg;
                if (data.group.id == group_id) {
                    msg = "{% trans 'Группа совпала:' %} " + data.group.name;
                }
                else if (data.group.name) {
                    msg = "{% trans 'Группа не совпала:' %} " + data.group.name;
                }
                else {
                    msg = "{% trans 'Группа не найдена.' %}";
                }
                alert(msg);
            })
        })
        .on('click', '.sample-delete', function(e) {
            e.preventDefault();
            result = confirm($(this).data('question') || _question);
            if (result) {
                $.ajax({method: 'delete'}).done(function(data) {
                    location = "{% url 'textrank:samples' %}";
                })
            }
        })
    ;
{% if DEMO_MODE and not user.is_authenticated %}
    $('form').on('submit', function(e) {
        e.preventDefault()
        alert("{% trans 'Это демо-режим, авторизуйтесь, чтобы изменять данные.' %}")
    })
{% endif %}
})
</script>
{% endnewlineless_javascript %}{% endblock %}
