{# -*- coding: utf-8 -*-

  This file is part of Invenio.
  Copyright (C) 2015-2020 CERN.

  Invenio is free software; you can redistribute it and/or modify it
  under the terms of the MIT License; see LICENSE file for more details.
#}

{% macro render_checkbox(field, label='') %}
  <div class="ui checkbox">
    {{ field(class_="form-control") }}
    {{ field.label }}
  </div>
{% endmacro %}

{% macro render_field_errors(errors) %}
  {% if errors is not mapping %}
  <div class="ui negative message" role="alert">
    {%- for error in errors %}
        <p>{{error}}</p>
    {%- endfor %}
  </div>
  {%- else %}
  <div class="ui negative message" role="alert">
    {%- for field, inner_errors in errors.items() %}
      {%- for error in inner_errors %}
        <p>{{error}}</p>
      {%- endfor %}
    {%- endfor %}
  </div>
  {%- endif %}
{% endmacro %}

{% macro render_field(field, icon="", placeholder='', autofocus=False) %}
  {%- if field.errors %}
    {{ render_field_errors(field.errors) }}
  {%- endif %}
  <div class="field ">
    {%- if field.widget.input_type == 'hidden' %}
      {{ field() }}
    {%- elif field.widget.input_type == 'checkbox' %}
      {{ render_checkbox(field, label=_(field.label.text | string)) }}
    {%- else %}
      {%- set extras = dict(autofocus="") if autofocus else dict() %}
      {%- set _placeholder = placeholder if placeholder else _(field.label.text | string) %}
      {{field(class_="form-control", placeholder=_placeholder, **extras)}}
      {%- if icon %}
      <i class="{{icon}}" aria-hidden="true" ></i>
      {%- endif%}
    {%- endif%}
  </div>
{% endmacro %}

{% macro oauth_button(name, next=None) %}
<div class="field">
  <a class="fluid ui basic button large"
     href="{{url_for('invenio_oauthclient.login', remote_app=name, next=next or request.referrer)}}">
    <i class="{{ name|lower() }} icon"></i> {{
      _('Sign in with %(title)s', title=config.OAUTHCLIENT_REMOTE_APPS[name]['title'])
    }}
  </a>
</div>
{% endmacro %}
