#!/usr/bin/env python3
#
# Format a result
#

import pscheduler

from validate import result_is_valid
from validate import MAX_SCHEMA

TEMPLATE = '''
{% if _mime_type == 'text/plain' %}

{% for path in result.paths %}
{%- if (result.paths | length) > 1 %}
Path {{ loop.index }}:

{% endif -%}
{% for hop in path -%}
{% if hop.ip is defined %}
{{ "%-8d%s (%s) %.1f ms" | format(
       loop.index,
       (hop.hostname or hop.ip),
       hop.ip,
       (iso8601_duration_seconds(hop.rtt) * 1000)
    ) }}
{%- if hop.mtu is defined -%}
{{ " mtu %d" | format (hop.mtu) }}
{%- endif -%}
{%- if hop.as is defined %}
{{ "%10sAS%d %s" | format("", hop.as.number, hop.as.owner) }}
{%- endif -%}
{%- else %}
{{ "%-8dNo Response" | format(loop.index) }}
{%- endif -%}
{% endfor -%}
{%- endfor -%}

{% elif _mime_type == 'text/html' %}

<table>
{% for path in result.paths %}
{%- if (result.paths | length) > 1 %}
<tr><th colspan="6">Path {{ loop.index }}</th></tr>
{% endif -%}
<tr>
  <th>Hop</th>
  <th>Host</th>
  <th>Address</th>
  <th>RTT (ms)</th>
  <th>MTU</th>
  <th>AS</th>
  <th>AS Owner</th>
</tr>
<tr>
{% for hop in path -%}
{% if hop.ip is defined %}
  <td>{{ loop.index }}</td>
  <td>{{ hop.hostname or hop.ip }}</td>
  <td>{{ hop.ip }}</td>
  <td>{{ "%.1f" | format(iso8601_duration_seconds(hop.rtt) * 1000) }}</td>
  <td>{{ hop.mtu if hop.mtu is defined else "&nbsp;" }}</td>
  {%- if hop.as is defined %}
  <td>{{ hop.as.number if hop.as.number is defined else "&nbsp;" }}</td>
  <td>{{ hop.as.owner if hop.as.owner is defined else "&nbsp;" }}</td>
  {% endif %}
{% else %}
  <td>{{ loop.index }}</td>
  <td colspan="6">No Response</td>
{% endif %}
</tr>
{% endfor -%}
{%- endfor -%}
</table>

{% else %}

{{ error('Unsupported MIME type "' + _mime_type + '"') }}

{% endif %}
'''

pscheduler.result_format_method(TEMPLATE, max_schema=MAX_SCHEMA, validator=result_is_valid)
