{# Render a form field's label with visual aid to see if it's required. #}
{%- macro field_label(f) -%}
  <label for="{{ f.id }}">
    {%- if f.flags.required -%}
      <strong>{{ f.label.text }}</strong>
    {%- else %}
      {{ f.label.text }}
    {%- endif %}
  </label>
{%- endmacro -%}


{# Render a form field's errors. #}
{%- macro field_errors(f) -%}
  {% if f.errors %}
    <ul class="list-unstyled text-danger">
      {% for error in f.errors %}
        <li>{{ error | e }}</li>
      {% endfor %}
    </ul>
  {% endif %}
{%- endmacro -%}


{# Render a form field. #}
{%- macro field(f, css_class='') -%}
  {{ f(class='form-control shadow-none ' + css_class, **kwargs) }}
{%- endmacro -%}


{# Render a checkbox field. #}
{%- macro checkbox_field(f, css_class='') -%}
  {{ f(type='checkbox', class='shadow-none ' + css_class, **kwargs) }} {{ f.label }}
{%- endmacro -%}


{# Render a form group with errors for various field types. #}
{%- macro form_group(f, css_class='') -%}
  {% if f.errors %}
    {% set css_class = css_class + ' is-invalid ' + kwargs.pop('class', '') %}
  {% endif %}

  {% if f.type == 'BooleanField' %}
    <div class="checkbox">
    {{ checkbox_field(f, css_class, **kwargs) }}
  {% else %}
    <div class="form-group">
    {{ field_label(f) }}
    {{ field(f, css_class, **kwargs) }}
  {% endif %}

    {{ field_errors(f) }}
    {{ caller () }}
  </div>
{%- endmacro %}


{# Render a form tag that contains a CSRF token and all hidden fields. #}
{%- macro form_tag(endpoint, fid='', css_class='', method='post') -%}
  <form action="{{ url_for(endpoint, **kwargs) }}" method="{{ method }}"
        id="{{ fid }}" class="{{ css_class }}" role="form">
    {{ form.hidden_tag() }}
    {{ caller () }}
  </form>
{%- endmacro -%}


{# Render a form for searching. #}
{%- macro search(endpoint) -%}
  {% call form_tag(endpoint, method='get') %}
    <label for="q"></label>
    <div class="input-group mb-5">
      <div class="input-group-prepend">
        <div class="input-group-text">
          <i class="fas fa-fw fa-search"></i>
        </div>
      </div>
      <input type="text" class="form-control"
             id="q" name="q" value="{{ request.args.get('q', '') }}"
             placeholder="Search by typing, then press enter...">
    </div>
  {% endcall %}
{%- endmacro -%}
