{% macro render_fields(source, form) %}
    {% for source_field_data in source %}
        {% if source_field_data is not string %}
            {% set field = source_field_data[0] %}
            {% set args = source_field_data[1:] %}
        {% else %}
            {% set field = source_field_data %}
            {% set args = [] %}
        {% endif %}
    {% if form[field].type == "BooleanField" %}
        {{ render_checkbox(form[field]) }}
    {% elif form[field].type == "SelectField" %}
        {{ render_select(form[field], *args) }}
    {% elif form[field].type == "RadioField" %}
        {{ render_radio(form[field]) }}
    {% else %}
        {{ render_field(form[field], *args) }}
    {% endif %}
    {% endfor %}
{% endmacro %}

{% macro render_radio(radiofield) -%}
    <div class="form-group {{ radiofield.name}}">
        <div class="col field_name {% if radiofield.errors %}has-danger{% endif %}">
            {{ radiofield.label(class="col-form-label", title=radiofield.description,
            **{"data-toggle":"tooltip", "data-placement":"right"}) }}
        </div>
        <div class="col">
            {% for radio in radiofield %}
                <div class="form-check-inline radio-inline">
                    {{ radio(class="radio") }} {{ radio.label(class="col-form-label") }}
                </div>
            {% endfor %}
        </div>
        <div class="col textError">
            {% if radiofield.form_errors %}
                {% for error in radiofield.form_errors %}
                    <div class="col-form-label text-danger">{{ error }}</div>
                {% endfor %}
            {% endif %}
        </div>
    </div>
{% endmacro %}

{% macro render_select(selectfield, style, formtype) %}
    <div class="form-group {{ formtype }} {{ selectfield.name}} {% if selectfield.errors %}has-danger{% endif %}" style="{{ style }}">
        <div class="col field_name">
            {{ selectfield.label(class="col-form-label", title=selectfield.description,
            **{"data-toggle":"tooltip", "data-placement":"right"}) }}
        </div>
        <div class="col">
            {{ selectfield(class="form-control",  **{"data-toggle":"tooltip", "data-placement":"top"}) }}
        </div>
        <div class="col textError">
            {% if selectfield.form_errors %}
                {% for error in selectfield.form_errors %}
                    <div class="col-form-label text-danger">{{ error }}</div>
                {% endfor %}
            {% endif %}
        </div>
    </div>
{% endmacro %}

{% macro render_field(field, style, formtype) %}
    <div class="form-group {{ formtype }} {{ field.name}} {% if field.errors %}has-danger{% endif %}" style="{{ style }}">
        <div class="col field_name">
            {{ field.label(title=field.description, class="col-form-label",
            **{"data-toggle":"tooltip", "data-placement":"right"}) }}
        </div>
        <div class="col" >
            {{ field(title=field.description, class="form-control", autocomplete="off", **{"data-toggle":"tooltip",
                    "data-placement":"top"}) }}
        </div>
        <div class="col textError">
            {% if field.form_errors %}
                {% for error in field.form_errors %}
                    <div class="col-form-label text-danger">{{ error }}</div>
                {% endfor %}
            {% endif %}
        </div>

    </div>
{% endmacro %}

{% macro render_checkbox(field) %}
    <div class="form-group {{ field.name}} {% if field.errors %}has-danger{% endif %}">
        <div class="col field_name">
            {{ field.label(title=field.description, class="col-form-label",
            **{"data-toggle":"tooltip", "data-placement":"right"}) }}
        </div>
        <div class="col">
            {{ field(title=field.description, **{"data-toggle":"tooltip",
                    "data-placement":"top"}) }}
        </div>
        <div class="col textError">
            {% if field.form_errors %}
                {% for error in field.form_errors %}
                    <div class="col-form-label text-danger">{{ error }}</div>
                {% endfor %}
            {% endif %}
        </div>
    </div>
{% endmacro %}

{% macro _render_resources_table(resource_table_data) %}
    {% if resource_table_data %}
   <table class="table table-bordered table-sm">
       <thead>
            <tr>
                {% for element in resource_table_data[0] %}
                    <th>{{ element }}</th>
                {% endfor %}
            </tr>
       </thead>
       <tbody>
       {% for row in resource_table_data[1:] %}
            <tr>
                <th scope="row">{{ row[0] }}</th>
                {% for element in row[1:-1] %}
                    <td>{{ element }}</td>
                {% endfor %}
                <td class="border-left {{ resource }}">{{ row[-1] }}</td>
            </tr>
       {% endfor %}
       </tbody>
   </table>
    {% endif %}
{% endmacro %}

{% macro render_quota_project(quota) %}
    <tr class="table-active">
        <td colspan="3">
            {% if not quota.abc_service.slug %}
                unknown
            {% else %}
                <a href="https://abc.yandex-team.ru/services/{{ quota.abc_service.slug }}" target="_blank">{{ quota.abc_service.hr_name or quota.abc_service.slug}}</a>
            {% endif %}
        </td>
        <td colspan="3">{{ _render_resources_table(quota.get_table_view()) }}</td>
        <td colspan="3">{{ _render_resources_table(quota.get_quota_table_view()) }}</td>
        <td colspan="3">{{ _render_resources_table(quota.get_free_table_view()) }}</td>
    </tr>
{% endmacro %}

{% macro render_quota_subproject(subproject) %}
  <tr style="background-color: #e7e7e7;">
      <td></td>
      <td colspan="2">
          <div class="d-flex">
          {% if not subproject.abc_service.slug %}
              unknown
          {% else %}
              <a href="https://abc.yandex-team.ru/services/{{ subproject.abc_service.slug }}" target="_blank">{{ subproject.abc_service.hr_name or subproject.abc_service.slug}}</a>
          {% endif %}
           </div>
      </td>
      <td colspan="3">
          {{ _render_resources_table(subproject.get_table_view()) }}
      </td>
      <td colspan="3"></td><td colspan="3"></td>
  </tr>
{% endmacro %}

{% macro render_quota_service(service) %}
<tr>
    <td colspan="2"></td>
    <td>
        <a href="https://saas-mon.n.yandex-team.ru/service_info?service={{ service.name }}&ctype={{ service.ctype }}" target="_blank">{{ service.ctype }}/{{ service.name }}</a>
    </td>
    <td colspan="3">
      {{ _render_resources_table(service.get_table_view()) }}
    </td>
    <td colspan="3"></td><td colspan="3"></td>
</tr>
{% endmacro %}


{% macro render_testing_form(form) %}
<form class="form-horizontal testing-form" role="form" method="post">
    {{  form.hidden_tag() }}
    <div class="form-group">
        <h5 class="text-center">Основные параметры</h5>
        {{ render_fields(["service_name", "abc_user_service", "abc_quota_service", "owners_list", "service_type"], form) }}
        <hr class="form-group"/>
        <h5 class="text-center">Ресурсы</h5>
        {{ render_field(form.instances_count) }}
        <hr class="form-group"/>
        {{ render_field(form.comment) }}
        <div class="form-group" style="color: red;">Если сервис не будет использоваться более 3 месяцев, он будет автоматически разобран</div>
        {{ form.submit(class_='btn btn-light') }}
    </div>
</form>
{% endmacro %}

{% macro render_prestable_form(form) %}
<form class="form-horizontal prestable-form" role="form" method="post">
  {{  form.hidden_tag() }}
   <div class="form-group">
       <h5 class="text-center">Основные параметры</h5>
       {{ render_fields(["service_name", "abc_user_service", "abc_quota_service", "owners_list", "service_ctype",
       "service_type", ["delivery_type", "", "prestable"]], form) }}
        <div class="prestable" id="delivery_param_label">
            <hr class="form-group"/>
            <h5 class="text-center">Параметры доставки данных</h5>
        </div>
       {{ render_fields(["yt_cluster", "yt_ferryman_format", ["logbroker_tvm_id", "display: none", ""], ["logbroker_traffic_volume", "display: none", ""]], form) }}
       <hr class="form-group"/>
       <h5 class="text-center">Параметры безопасности</h5>
       {{ render_fields(["service_tvm", "service_saas_tvm"], form) }}
       <hr class="form-group"/>
       <h5 class="text-center">Ресурсы</h5>
       {{ render_fields(["instances_count", "memory_requirements", "cpu_requirements", "replicas_per_dc"], form) }}
       <hr class="form-group"/>
       {{ render_field(form.comment) }}
       {{ form.submit(class_='btn btn-light') }}
    </div>
</form>
{% endmacro %}

{% macro render_production_form(form) %}
<form class="form-horizontal production-form" role="form" method="post">
  {{  form.hidden_tag() }}
   <div class="form-group">
       <h5 class="text-center">Основные параметры</h5>
       {{ render_fields(["service_name", "abc_user_service", "abc_quota_service", "owners_list", "service_ctype",
       "service_type", ["delivery_type", "", "production"]], form) }}
        <div class="production" id="delivery_param_label">
            <hr class="form-group"/>
            <h5 class="text-center">Параметры доставки данных</h5>
        </div>
       {{ render_fields(["yt_cluster", "yt_ferryman_format", ["logbroker_tvm_id", "display: none", ""], ["logbroker_traffic_volume", "display: none", ""]], form) }}
       <hr class="form-group"/>
       <h5 class="text-center">Параметры безопасности</h5>
       {{ render_fields(["service_tvm", "service_saas_tvm"], form) }}
       <hr class="form-group"/>
       <h5 class="text-center">Параметры SLA</h5>
       {{ render_fields(["search_rps", "index_size", "maxdocs", "search_q_99_ms", "search_q_999_ms"], form) }}
       <hr class="form-group"/>
       <h5 class="text-center">Ресурсы</h5>
       <a class="btn btn-light btn-sm calcRes calcBySLA" role="button" aria-expanded="false" data-placement="right" data-toggle="tooltip" title="Произвести примерный расчет необходимых ресурсов для сервиса опираясь на параметры SLA, заданные выше">Рассчитать из SLA</a>
       <div class="col resourcesTextError"></div>
       {{ render_fields(["instances_count", "memory_requirements", "cpu_requirements", "replicas_per_dc"], form) }}
       <hr class="form-group"/>
       {{ render_field(form.comment) }}
       {{ form.submit(class_='btn btn-light') }}
    </div>
</form>
{% endmacro %}

{% macro render_namespace_form(form) %}
<form class="form-horizontal namespace-form" role="form" method="post">
  {{  form.hidden_tag() }}
   <div class="form-group">
       <h5 class="text-center">Основные параметры</h5>
       {{ render_fields(["namespace_name", "owners_list", "ferryman_service"], form) }}
       <hr class="form-group"/>
       <h5 class="text-center">Ресурсы</h5>
       {{ render_fields(["namespace_size", "namespace_doccount"], form) }}
       <hr class="form-group"/>
       {{ render_field(form.comment) }}
       {{ form.submit(class_='btn btn-light') }}
   </div>
</form>
{% endmacro %}

{% macro render_shooting_form(form) %}
<br>
<form class="form-horizontal custom-shooting-form" role="form" method="post">
    {{ form.hidden_tag() }}
    <div class="form-group">
        <h5 class="text-center">Настройки стрельбы</h5>
        {{ render_fields(["ammo_file", "service", "source_service", "ticket", "locations", "ctype", "target_rps",
        "store_requests_info", "requests_info_find_by"], form) }}
        <hr class="form-group"/>
        {{ form.submit(class_='btn btn-light') }}
    </div>
</form>
{% endmacro %}

{% macro render_regular_shooting_form(regular_form) %}
<br>
<form class="form-horizontal regular-shooting-form" role="form" method="post">
    {{ regular_form.hidden_tag() }}
    <div class="form-group">
        <h5 class="text-center">Регулярные настройки</h5>
        {% if regular_form.scheduler_id.data %}
            {{ render_fields(["scheduler_id", "ammo_file", "start_time", "repetition_interval", "service",
            "source_service", "ticket", "locations", "ctype", "target_rps",
            "responsibles", "notify_time", "send_results_to_uchenki", "status"], regular_form) }}
        {% else %}
            {{ render_fields(["ammo_file", "start_time", "repetition_interval", "service",
            "source_service", "ticket", "locations", "ctype", "target_rps",
            "responsibles", "notify_time", "send_results_to_uchenki", "status"], regular_form) }}
        {% endif %}
        <hr class="form-group"/>
        {{ regular_form.submit(class_='btn btn-light') }}
    </div>
</form>
{% endmacro %}

{% macro render_shooting_table(table) %}
<br>
<h5 class="text-center">Таблица регулярных стрельб</h5>
<br>
<table style="text-align: center;vertical-align: middle;width: 100%">
    <tr>
        {% for el in ["Scheduler id", "Service", "Ctype", "Ticket", "Target rps", "Start time"] %}
            <td>{{ el }}</td>
        {% endfor %}
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
{% for field, shooting, rps in table %}
    <tr>
        <td><a href="https://sandbox.yandex-team.ru/scheduler/{{field['scheduler_id']}}">{{ field['scheduler_id'] }}</a></td>
        <td>
            <a href="https://saas-mon.n.yandex-team.ru/deploy?ctype={{field['ctype']}}&service={{field['service']}}">
                {{ field['service'] }}</a>
        </td>
        <td>{{ field['ctype'] }}</td>
        <td><a href="http://st.yandex-team.ru/{{field['ticket']}}">{{ field['ticket'] }}</a></td>
        <td>{{ rps }}</td>
        <td>{{ field['next_time'] }}</td>
        {% if field['status'] %}
        <td>
            <a href="" role="button" id="{{field['scheduler_id']}}" class="Request turnShootings btn btn-light btn-sm">Запустить</a>
        </td>
        {% else %}
        <td>
            <a href="" role="button" id="{{field['scheduler_id']}}" class="Request turnShootings btn btn-light btn-sm">Остановить</a>
        </td>
        {% endif %}
        <td>
            <a href="" role="button" id="{{field['scheduler_id']}}" class="Request editShooting btn btn-light btn-sm">Редактировать</a>
        </td>
        <td>
            <a href="" role="button" id="{{field['scheduler_id']}}" class="Request deleteShooting btn btn-light btn-sm">Удалить</a>
        </td>
        <td>
            {% if shooting %}
                {% if shooting['status'] in ["EXCEPTION", "STOPPED"] %}
                    <a href="https://sandbox.yandex-team.ru/task/{{shooting['id']}}"><span
                        class="dot" style="height: 12px;width: 12px;background-color: red;border-radius: 50%;display: inline-block;"></span></a>
                {% elif shooting['status'] == "SUCCESS" %}
                    <a href="https://sandbox.yandex-team.ru/task/{{shooting['id']}}"><span
                        class="dot" style="height: 12px;width: 12px;background-color: green;border-radius: 50%;display: inline-block;"></span></a>
                {% else %}
                    <a href="https://sandbox.yandex-team.ru/task/{{shooting['id']}}"><span
                        class="dot" style="height: 12px;width: 12px;background-color: darkgrey;border-radius: 50%;display: inline-block;"></span></a>
                {% endif %}
            {% endif %}
        </td>
    </tr>
{% endfor %}
</table>
<br>
<a href="#" role="button" id="new" class="Request editShooting btn btn-light btn-sm">Добавить</a>
{% endmacro %}

{% macro nav_link(endpoint, name) %}
    {% if request.endpoint.endswith(endpoint) %}
      <li class="nav-item active"><a class="nav-link" href="{{ url_for(endpoint) }}">{{name}}</a></li>
    {% else %}
      <li class="nav-item"><a class="nav-link" href="{{ url_for(endpoint) }}">{{name}}</a></li>
    {% endif %}
{% endmacro %}

{% macro findkey_form(findkey_form, admin_mode=False) %}
<br>
<form class="form-horizontal findkey-form" role="form" method="post">
  {{  findkey_form.hidden_tag() }}
   <div class="form-group">
       <h5 class="text-center">Настройки поиска</h5>
       {% set fields_to_render = ["service", "ctype", "url", "kps", "yql_day_count", "use_tvm", "src_tvm_id", "ignore_dc"] %}
       {{ render_fields(fields_to_render, findkey_form) }}
       {{ render_fields(["kv_or_ft"], findkey_form) }}
       {% if admin_mode %}
            <hr class="form-group"/>
            <h5 class="text-center">Продвинутые настройки (Только для Администраторов SaaS)</h5>
            {{ render_fields(["dst_tvm_id", "yql_df_dst_table", "yql_index_dst_table", "ferryman_host", "ferryman_show_found"], findkey_form) }}
       {% endif %}
       <hr class="form-group"/>
       {{ findkey_form.submit(class_='btn btn-light') }}
   </div>
</form>
{% endmacro %}
