{% from 'macros/_commodity_macros.html' import render_num, render_amount %}

{% set short_type = {
   'balance': 'Bal',
   'close': 'Close',
   'document': 'Doc',
   'note': 'Note',
   'open': 'Open',
} %}

{% macro _account_link(name) %}<a href='{{ url_for('account', name=name) }}'>{{ name }}</a>{% endmacro %}

{% macro _render_metadata_indicators(metadata) -%}
{% for key, value in metadata %}
<span class='metadata-indicator' title='{{ key }}: {{ value }}'>{{ key[:2] }}</span>
{% endfor %}
{%- endmacro %}

{% macro _render_metadata(metadata, entry_hash=None) -%}
{% if metadata %}
<dl class='metadata'>
  {% for key, value in metadata %}
  <dt>{{ key }}:</dt>
  <dd>
  {%- if key.startswith('document') %}<a class='filename' data-remote target=_blank href='{{ url_for('statement', entry_hash=entry_hash, key=key) }}'>{{ value }}</a>
  {% elif value is string and (value.startswith('http://') or value.startswith('https://')) %}<a class='url' data-remote target=_blank rel='noopener noreferrer' href='{{ value }}'>{{ value }}</a>
  {% else %}
    {{ value }}
  {% endif -%}
  </dd>
  {% endfor %}
</dl>
{% endif %}
{% endmacro %}

{% macro _render_tags_links(entry) -%}
{% for tag in entry.tags|sort %}<span class='tag'>#{{ tag }}</span>{% endfor %}
{% for link_ in entry.links|sort %}<span class='link'>^{{ link_ }}</span>{% endfor %}
{%- endmacro %}

{% macro journal_table_contents(entries, show_change_and_balance=False, ledger=None) %}
{% set ledger = ledger or g.ledger %}
{% set show_metadata_indicators = ledger.fava_options.show_metadata_indicators %}
{% autoescape false %}
{% for entry in entries %}
    {% if show_change_and_balance %}
        {% set index, entry, change, balance = entry %}
    {% else %}
        {% set index, entry = entry %}
    {% endif %}
    {% set type = entry.__class__.__name__.lower() %}
    {% set metadata_items = entry.meta|meta_items %}
    {% set entry_hash = entry|hash_entry -%}
    <li class='{{ type }} {{ entry.type or '' }} {{ entry.flag|flag_to_type if entry.flag else '' }}{{ ' linked' if entry.tags and 'linked' in entry.tags else '' }}{{ ' discovered' if entry.tags and 'discovered' in entry.tags else '' }}'>
        <p>
        <span class='datecell' data-sort-value='{{ index }}'><a href='#context-{{ entry_hash }}'>{{ entry.date }}</a></span>
        <span class='flag'>{% if type == 'transaction' %}{{ entry.flag }}{% else %}{{ short_type.get(type, type[:3]) }}{% endif %}</span>
        <span class='description'>
        {% if type == 'open' or type == 'close' %}
            {{ _account_link(entry.account) }}
        {% elif type == 'note' %}
            {{ entry.comment }}
        {% elif type == 'query' %}
          <a href='{{ url_for('report', report_name='query', query_string='run "{}"'.format(entry.name)) }}'>{{ entry.name }}</a>
        {% elif type == 'pad' %}
            {{ _account_link(entry.account) }}&nbsp;from&nbsp;{{ _account_link(entry.source_account) }}
        {% elif type == 'custom' %}
          <strong>{{ entry.type }}</strong>
          {%- for value in entry['values'] -%}
            &nbsp;{% if value.dtype|string == "<AccountDummy>" %}{{ _account_link(value.value) }}
            {%- elif value.dtype|string == "<class 'beancount.core.amount.Amount'>" %}{{ render_amount(ledger, value.value) }}
            {%- elif value.dtype|string == "<class 'str'>" %}"{{ value.value }}"
            {%- elif value.dtype|string == "<class 'bool'>" %}{{ value.value }}
            {%- elif value.dtype|string == "<class 'datetime.date'>" %}{{ value.value }}{% endif -%}
          {%- endfor -%}
        {% elif type == 'document' %}
            {{ _account_link(entry.account) }}
            <a class='filename' data-remote target=_blank href='{{ url_for('document', filename=entry.filename) }}'>{{ entry.filename|basename }}</a>
            {{ _render_tags_links(entry) }}
        {% elif type == 'balance' %}
            {{ _account_link(entry.account) }}
            {% if entry.diff_amount %}
            <span class='spacer'></span>
            accumulated <span class='num'>{{ (entry.amount.number + entry.diff_amount.number)|format_currency(entry.amount.currency) }} {{ entry.amount.currency }}</span>
            {% endif %}
        {% elif type == 'transaction' %}
            <strong class='payee'>{{ entry.payee or '' }}</strong>{% if entry.payee and entry.narration %}<span class='separator'></span>{% endif %}{{ entry.narration or '' }}
            {{ _render_tags_links(entry) }}
        {% endif %}
        </span>
        <span class='indicators'>
          {%- if show_metadata_indicators %}{{- _render_metadata_indicators(metadata_items) -}}{% endif -%}
          {%- for posting in entry.postings -%}
          <span{% if posting.flag %} class='{{ posting.flag|flag_to_type }}'{% endif %}></span>
          {%- if show_metadata_indicators %}{{- _render_metadata_indicators(posting.meta|meta_items) -}}{% endif -%}
          {%- endfor -%}
        </span>
        {% if type == 'balance' %}
          {{ render_amount(ledger, entry.amount, 'num bal' + (' pending' if entry.diff_amount else '')) }}
            {% if entry.diff_amount %}
              <span class='change num bal pending'>
              {{- render_num(ledger, entry.diff_amount.currency, entry.diff_amount.number) -}}
              </span>
            {% else %}
              <span class='change num'></span>
            {% endif %}
            {% if not show_change_and_balance %}
              <span class='change num'></span>
            {% endif %}
        {% endif %}
        {% if show_change_and_balance %}
          {% if type == 'transaction' %}
            <span class='change num'>
            {%- for currency, number in change.items() %}{{ render_num(ledger, currency, number) }}<br>{% endfor -%}
            </span>
          {% endif %}
          <span class='num'>
          {%- for currency, number in balance.items() %}{{ render_num(ledger, currency, number) }}<br>{% endfor -%}
          </span>
        {% endif %}
        </p>
        {{ _render_metadata(metadata_items, entry_hash) }}
        {% if entry.postings %}
          <ul class='postings'>
        {% for posting in entry.postings %}
        <li{% if posting.flag %} class='{{ posting.flag|flag_to_type }}'{% endif %}>
            <p>
                <span class='datecell'></span>
                <span class='flag'>{{ posting.flag or '' }}</span>
                <span class='description'>{{ _account_link(posting.account) }}</span>
                {# We want the output these amounts with the same precision as in the input file.
                   For computed values this might give a lot of digits, so format the price using the DisplayContext for now.#}
                <span class='num'>{% if posting.units %}{{ posting.units.number|incognito }} {{ posting.units.currency }}{% endif %}</span>
                <span class='num'>{{ posting.cost.number|incognito }} {{ posting.cost.currency }}
                    {{- ', {}'.format(posting.cost.date) if posting.cost.date else '' }}
                    {{- ', "{}"'.format(posting.cost.label) if posting.cost.label else '' }}</span>
                {{ render_amount(ledger, posting.price) }}
            </p>
            {{ _render_metadata(posting.meta|meta_items) }}
        </li>
        {% endfor %}
        </ul>
        {% endif %}
    </li>
{%- endfor %}
{% endautoescape %}
{%- endmacro %}
