{% macro render_revision(revision, list_link, search, index, organization_id) %}
{% if revision %}
    <span class="badge {{ "badge-success" if revision.status == "active" else ("badge-warning" if revision.status == "new" else "badge-important" if revision.status == "broken" else "badge" if revision.status == "deleted" else "badge-info" if revision.status == "ready" else "badge-inverse") }}">{{ revision.id }}</span>
    <a href="{{ url("isearch-sources-revision", revision.search, revision.index or 'default', revision.id) }}">
        <span class="icon-list"></span>
    </a>
    {% set search = revision.search %}
    {% set index = revision.index %}
{% else %}(нет){% endif %}
{% if list_link %}
    <a href="{{ url('isearch-sources-revision-list', search, index or 'default') }}?organization_id={{ organization_id }}" class="pull-right">
        <span class="icon-book"></span>
    </a>
    {% endif %}
{% endmacro %}

{% macro render_status(record=None, use_status=None, link_type=None, check_swarm=False) -%}
    {% with status = use_status or record.status %}
        <span class="label {% if status == 'done' %}label-success{% elif status in ('new', 'stop') %}label-warning{% elif status == 'cancel' %}label-primary{% elif status == 'retry' %}label-info{% else %}label-important{% endif %}">
            {{ caller() }}
        </span>
    {% endwith %}
    {% if record and check_swarm and not record.swarm %}
        &nbsp;<span class="label label-primary">old</span>
    {% endif %}
    {% if record and link_type %}
        {% if link_type == "indexation" %}
            <a href="{{ url('isearch-sources-indexation', record.search, record.index or 'default', record.id) }}">
        {% else %}
            <a href="{{ url('push_info', record.id) }}">
        {% endif %}
                <span class="icon-list"></span>
            </a>
    {% endif %}
{%- endmacro %}


{% macro new_indexation(id, index, backend, defaults, suffixes, organization_id) -%}
<span class="muted"><a href="#new_{{ backend }}_{{ id }}_{{ index }}" data-toggle="modal"><i class="icon-play"></i></a> {{ caller() }}</span>
<div id="new_{{ backend }}_{{ id }}_{{ index }}" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="new_{{ backend }}_{{ id }}_{{ index }}" aria-hidden="true">
    <form method="POST" action="{{ url('isearch-sources-new-indexation') }}" style="margin: 0px;">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3>Индексация {{ id }} ({{ index or "default" }})</h3>
        </div>
        <div class="modal-body">
            <fieldset>
                <label class="checkbox">
                    <input name="nort" type="checkbox" checked/> Отключить реалтайм
                </label>
                <label class="checkbox">
                    <input name="global_" type="checkbox" {% if defaults.global %}checked{% endif %}/> Использовать только глобальные очереди
                </label>
                <label class="checkbox">
                    <input name="no_check" type="checkbox" {% if defaults.no_check %}checked{% endif %}/> Не использовать check
                </label>
                <div class="control-group">
                    <div class="controls">
                      <textarea name="comment" id="comment" rows="3" placeholder="Комментарий"></textarea>
                    </div>
                </div>
            </fieldset>
            <div class="accordion" id="accordion_{{ id }}_{{ index }}">
                <div class="accordion-group">
                    <div class="accordion-heading">
                        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_{{ id }}_{{ index }}" href="#params_{{ id }}_{{ index }}">
                            Параметры индексации
                        </a>
                    </div>
                    <div id="params_{{ id }}_{{ index }}" class="accordion-body collapse">
                        <div class="accordion-inner">
                            <fieldset>
                                <div class="control-group">
                                    <div class="controls">
                                      <input type="text" class="input-mini" id="threads" name="threads" value="{{ defaults.threads }}"><span class="help-inline">Количество тредов</span>
                                    </div>
                                    <div class="controls">
                                      <select name="priority" class="input-mini">
                                        {% for i in range(0, 10, 3) %}<option {% if i==9 %}selected{% endif %}>{{i}}</option>{% endfor %}
                                    </select><span class="help-inline">Приоритет (меньше - выше)</span>
                                    </div>
                                    <div class="controls">
                                        <select name="load_percent" class="input-mini">
                                            {% for i in (100, 75, 50, 25) %}
                                            <option value="{{ i }}"
                                                    {% if i==50 %}selected{% endif %}>{{i}}%</option>
                                            {% endfor %}
                                        </select><span class="help-inline">Процент нагрузки</span>
                                    </div>
                                    <div class="controls">
                                        <select name="suffix" class="input">
                                            {% for suffix in suffixes %}
                                            <option value="{{ suffix }}">{{ suffix }}</option>
                                            {% endfor %}
                                        </select><span class="help-inline">Суффикс волка для запуска</span>
                                    </div>
                                    <div class="controls">
                                        <label class="checkbox"><input type="checkbox" name="document_storages" value="saas"/>Saas</label>
                                        <label class="checkbox"><input type="checkbox" name="document_storages" value="yt"/>YT</label>
                                        <label class="checkbox"><input type="checkbox" name="document_storages" value="logbroker" checked/>Logbroker</label>
                                        <span class="help-block">Куда отправлять документы</span>
                                    </div>
                                    <label class="checkbox">
                                        <input name="flush" type="checkbox" {% if defaults.flush %}checked{% endif %}/> Флашить в сторадж после индексации
                                    </label>
                                    <label class="checkbox">
                                        <input name="from_cache" type="checkbox" {% if defaults.from_cache %}checked{% endif %}/> Индексировать из кеша
                                    </label>
                                    <input name="cache_table" placeholder="//home/intrasearch/data/production/wiki-" value=""/>
                                    <span class="help-block">Таблица на YT, из которой взять данные</span>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                </div>
                <div class="accordion-group">
                    <div class="accordion-heading">
                        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_{{ id }}_{{ index }}" href="#limit_{{ id }}_{{ index }}">
                        Лимиты
                        </a>
                    </div>
                    <div id="limit_{{ id }}_{{ index }}" class="accordion-body collapse">
                        <div class="accordion-inner">
                            <fieldset>
                                <input name="organizations" placeholder="mockorg,storg" value="{% if organization_id %}{{ organization_id }}{% endif %}"/>
                                <span class="help-block">Организации (directory_id или label)</span>

                                <input name="limit" placeholder="1000" value="{{ defaults.limit or '' }}"/>
                                <span class="help-block">Количество документов</span>

                                <label class="checkbox">
                                    <input name="use_ts" type="checkbox" {% if defaults.use_ts %}checked{% endif %}> Только страницы измененные с начала последней удачной индексации, или
                                </label>

                                <input name="ts" placeholder="%Y-%m-%d %H:%M:%S" value="{{ defaults.limit or '' }}"/>
                                <span class="help-block">Документы измененные после данной даты</span>

                                <input name="keys" placeholder="isearch,wiki"/>
                                <span class="help-block">Какие части источника индексировать (очереди etc)</span>
                            </fieldset>
                        </div>
                    </div>
                </div>
                <div class="accordion-group">
                    <div class="accordion-heading">
                        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_{{ id }}_{{ index }}" href="#revision_{{ id }}_{{ index }}">
                        Ревизия и сервис
                        </a>
                    </div>
                    <div id="revision_{{ id }}_{{ index }}" class="accordion-body collapse">
                        <div class="accordion-inner">
                            <fieldset>
                                <label class="checkbox">
                                    <input name="shadow_revision" type="checkbox" {% if defaults.shadow_revision %}checked{% endif %}/> Не делать ревизию активной
                                </label>
                                <label class="checkbox">
                                    <input name="new_revision" type="checkbox" {% if defaults.new_revision %}checked{% endif %}/> Создать новую ревизию для индекса
                                </label>
                                <input name="revision_id" value="{{ defaults.revision_id or '' }}"/>
                                <span class="help-block">id ревизии для индексации</span>
                                <input name="service" value="{{ defaults.service or '' }}"/>
                                <span class="help-block">в какой сервис индексировать</span>
                            </fieldset>
                        </div>
                    </div>
                </div>
                <div class="accordion-group">
                    <div class="accordion-heading">
                        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_{{ id }}_{{ index }}" href="#lock_{{ id }}_{{ index }}">
                            Локи
                        </a>
                    </div>
                    <div id="lock_{{ id }}_{{ index }}" class="accordion-body collapse">
                        <div class="accordion-inner">
                            <fieldset>
                                <input name="lock_timeout" placeholder="1h" value="{{ defaults.lock_timeout or '' }}"/>
                                <span class="help-block">Таймаут (s|m|h|d)</span>
                                <label class="checkbox">
                                    <input name="nolock" type="checkbox" {% if defaults.nolock %}checked{% endif %}/> Не использовать лок
                                </label>
                            </fieldset>
                        </div>
                    </div>
                </div>
                <div class="accordion-group">
                    <div class="accordion-heading">
                        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_{{ id }}_{{ index }}" href="#debug_{{ id }}_{{ index }}">
                            Отладка
                        </a>
                    </div>
                    <div id="debug_{{ id }}_{{ index }}" class="accordion-body collapse">
                        <div class="accordion-inner">
                            <fieldset>
                                <label class="checkbox">
                                    <input name="debug" type="checkbox" {% if defaults.debug %}checked{% endif %}/> Расширенный лог
                                </label>
                                <label class="checkbox">
                                    <input name="dry_run" type="checkbox" {% if defaults.dry_run %}checked{% endif %}/> Ничего никуда не отправлять (dry run)
                                </label>
                            </fieldset>
                        </div>
                    </div>
                </div>
            </div>
            <fieldset>
                <input type="hidden" name="search" value="{{ id }}" />
                <input type="hidden" name="index" value="{{ index }}" />
            </fieldset>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" type="submit">Поехали</button>
        </div>
    </form>
</div>
{%- endmacro %}

{% macro repeat_indexation(indexation) %}
<span class="muted"><a href="#repeat_{{ indexation.id }}" data-toggle="modal"><i class="icon-repeat"></i></a> {{ caller() }}</span>
<div id="repeat_{{ indexation.id }}" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="repeat_{{ indexation.id }}" aria-hidden="true">
    <form method="POST" action="{{ url('isearch-sources-repeat-indexation') }}" style="margin: 0px;">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3>Повтор индексации #{{ indexation.id }}</h3>
        </div>
        <div class="modal-body">
            <fieldset>
                <div class="control-group">
                    <div class="controls">
                        <span class="help-block">Комментарий</span>
                        <textarea name="comment" id="comment" rows="3">{{ indexation.comment }}</textarea>
                    </div>
                </div>
                <input type="hidden" name="original_id" value="{{ indexation.id }}" />
            </fieldset>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" type="submit">Поехали</button>
        </div>
    </form>
</div>
{%- endmacro %}

{% macro stop_indexation(indexation) %}
<span class="muted"><a href="#stop_{{ indexation.id }}" data-toggle="modal"><i class="icon-trash"></i></a> {{ caller() }}</span>
<div id="stop_{{ indexation.id }}" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="stop_{{ indexation.id }}" aria-hidden="true">
    <form method="POST" action="{{ url('isearch-sources-stop-indexation') }}" style="margin: 0px;">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3>Управление индексацией {{ indexation.search }} ({{ indexation.index or "default" }})</h3>
        </div>
        <div class="modal-body">
            <p style="font-size:14px; font-weight:normal">Индексация {{ indexation.id }} идет уже {{ human_delta((indexation.end_time or now()) - indexation.start_time) }}, начиная с {{ indexation.start_time }}</p>
            <fieldset>
                <input type="hidden" name="indexation_id" value="{{ indexation.id }}" />
            </fieldset>
        </div>
        <div class="modal-footer">
            {% if indexation.status == 'stop' %}
            <button class="btn btn-success" type="submit" name='status' value='done'>Done</button>
            {% endif %}
            {% if indexation.status == 'new' %}
            <button class="btn btn-warning" type="submit" name='status' value='stop'>Stop</button>
            {% endif %}
            <button class="btn btn-danger" type="submit" name='status' value='fail'>Fail</button>
        </div>
    </form>
</div>
{%- endmacro %}

{% macro stages_table(stages, plot_data) %}
<div class="row-fluid">
    <div class="chart">
        <table class="table table-bordered table-hover">
            {% for stage_type, info in stages %}
            {% if loop.index == 1 %}
            <tr><th></th>{% for status, count in info %}<th>{{ status }}</th>{% endfor %}</tr>
            {% endif %}
            <tr>
                <th>{{ stage_type }}
                    <span class="icon-signal stage-chart-btn"
                          data-stage="{{ stage_type }}"
                          style="cursor: pointer"
                          ></span>
                </th>
                {% for status, count in info %}
                <td>{{ intformat(count) }}</td>
                {% endfor %}
            </tr>
            {% endfor %}
        </table>
        <div class="plot-data" style="display:none">{{ plot_data }}</div>
        <div class="plot-container"></div>
    </div>
</div>
{% endmacro %}

{% macro doc_counter(name, revision_id, indexation_id, use_indexstat='false') %}
<i class="icon-refresh counter" onclick="get_count('{{ name }}', {{ revision_id }}, '{{ indexation_id }}', {{ use_indexstat }});"></i>&nbsp;<span id="{{ name }}_text"></span><span class="pull-right"><a id="{{ name }}_url" href="">url</a></span>
{% endmacro %}

{% macro fail_indexations(search, index) %}
<span class="muted"><a href="#fail_indexations" data-toggle="modal"><i class="icon-trash"></i></a> {{ caller() }}</span>
<div id="fail_indexations" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="fail_indexations" aria-hidden="true">
    <form method="POST" action="{{ url('isearch-sources-fail-indexations') }}">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3>Управление индексациями</h3>
        </div>
        <div class="modal-body">
            <fieldset>
                <input name="threshold" placeholder="1h"/><span class="help-inline">*</span>
                <span class="help-block">Порог (s|m|h|d)</span>
                <input name="search" value="{{ search }}" />
                <span class="help-block">Источник</span>
                <input name="index" value="{{ index }}" />
                <span class="help-block">Индекс</span>
            </fieldset>
        </div>
        <div class="modal-footer">
            <button class="btn btn-danger" type="submit">Fail them all</button>
        </div>
    </form>
</div>
{% endmacro %}

{% macro manage_revision(revision) %}
<form  method="POST" action="{{ url('isearch-sources-manage-revision') }}" style="margin:0;">
    <input type="hidden" name="revision_id" value="{{ revision.id }}"/>
    <input type="hidden" name="search" value="{{ revision.search }}"/>
    <input type="hidden" name="index" value="{{ revision.index }}"/>
    {% if revision.status != 'active' %}
    <button class="btn btn-success" id="on_air" name="on_air" value="1">On air!</button>
    {% endif %}
    {% if revision.status != 'deleted' %}
    <button class="btn btn-danger" name="delete" value="1">Delete</button>
    {% endif %}
</form>
{% endmacro %}

{% macro admin_org_link(org, text='') %}
    <a href="{{ url('isearch-organization-details', org.id) }}">
        {% if text %}{{ text }}{% else %}{% if org.label %}{{ org.label }}{% else %}{{ org.directory_id }}{% endif %}{% endif %}
    </a>
{% endmacro %}

{% macro render_push_meta(push) %}
    <div class="accordion-group">
        <div class="accordion-heading">
            <div class="accordion-toggle">
                <div class="pull-right">
                    <a target="_blank" href="{{ url('push_meta_json', push.id) }}"><small>(json)</small></a>
                </div>
                <a data-toggle="collapse" href="#meta_{{ push.id }}">
                    Expand <i class="icon-chevron-down"></i>
                </a>
            </div>
        </div>
        <div id="meta_{{ push.id }}" class="accordion-body collapse">
            <pre><code>{{ push.meta|to_json|e }}</code></pre>
        </div>
    </div>
{% endmacro %}

{% macro render_push_actions(push) %}
    <div class="btn-group">
        <form method="POST" action="{{ url('push_restart', push.id) }}" style="margin-right: 5px; float: left">
            <input class="btn btn-primary" type="submit" value="Перезапустить" />
        </form>
        <form method="POST" action="{{ url('push_mark_as_known', push.id) }}">
            <input class="btn btn-danger" type="submit" value="Сфейлить окончательно" />
        </form>
    </div>
{% endmacro %}
