{% import 'macros/_commodity_macros.html' as commodity_macros %}

{% 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(entries, show_change_and_balance=False, ledger=None) %}
{% set ledger = ledger or g.ledger %}
{% autoescape false %}
<fava-journal>
<ol class="flex-table journal">
    <li class="head">
        <p>
        <span class="datecell" data-sort="num" data-sort-name="date" data-order="asc">{{ _('Date') }}</span>
        <span class="flag" data-sort="string" data-sort-name="flag">{{ _('F') }}</span>
        <span class="description" data-sort="string" data-sort-name="narration">{{ _('Payee/Narration') }}</span>
        <span class="num">{{ _('Position') }}</span>
        <span class="num">{{ _('Price') }}</span>
        <span class="num">{{ _('Cost') }}</span>
        {% if show_change_and_balance %}
        <span class="num">{{ _('Change') }}</span>
        <span class="num">{{ _('Balance') }}</span>
        {% endif %}
        </p>
    </li>
{% for entry in entries %}
    {% if show_change_and_balance %}
        {% set entry, change, balance = entry %}
    {% endif %}
    {% set type = entry.__class__.__name__.lower() %}
    {% set metadata_items = entry.meta|meta_items %}
    {% if type == 'price' %}{% continue %}{% endif %}
    {% 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={{ loop.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 != 'transaction' %}"{% else %} droptarget" data-entry="{{ entry_hash }}" data-entry-date="{{ entry.date }}" data-account-name="{{ entry.postings[0].account if entry.postings else "" }}"{% endif %}>
        {% 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'>" %}{{ commodity_macros.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, show_if_zero=True) }} {{ 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">
          {{ render_metadata_indicators(metadata_items) }}
          {% for posting in entry.postings %}
          <span{% if posting.flag %} class="{{ posting.flag|flag_to_type }}"{% endif %}></span>
          {{ render_metadata_indicators(posting.meta|meta_items) }}
          {% endfor %}
        </span>
        {% if type == 'balance' %}
          {{ commodity_macros.render_amount(ledger, entry.amount, 'num bal' + (' pending' if entry.diff_amount else '')) }}
        {% endif %}
        {% if show_change_and_balance %}
          <span class="change num">
          {%- for currency, number in change.items() %}{{ commodity_macros.render_num(ledger, currency, number) }}<br>{% endfor -%}
          </span>
          <span class="num">
          {%- for currency, number in balance.items() %}{{ commodity_macros.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 droptarget" data-entry="{{ entry_hash }}" data-account-name="{{ posting.account }}" data-entry-date="{{ entry.date }}">{{ 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">{{ posting.units or '' }}</span>
                {{ commodity_macros.render_amount(ledger, posting.price) }}
                <span class="num">{{ posting.cost.number }} {{ posting.cost.currency }}
                    {{- ', {}'.format(posting.cost.date) if posting.cost.date else '' }}
                    {{- ', "{}"'.format(posting.cost.label) if posting.cost.label else '' }}</span>
                {% if show_change_and_balance %}
                <span class="change num"></span>
                <span class="num"></span>
                {% endif %}
            </p>
            {{ render_metadata(posting.meta|meta_items) }}
        </li>
        {% endfor %}
        </ul>
        {% endif %}
    </li>
{% endfor %}
</ol>
</fava-journal>
{% endautoescape %}
{%- endmacro %}
