{#  This file was part of Flask-Bootstrap and was modified under the terms of
 its BSD License. Copyright (c) 2013, Marc Brinkmann. All rights reserved. #}

{# This file was part of Bootstrap-Flask and was modified under the terms of
 its MIT License. Copyright (c) 2018 Grey Li. All rights reserved.#}
 
{% from 'fomantic/utils.html' import render_ui_icon, arg_url_for %}


{% macro build_url(endpoint, model, pk, url_tuples) %}
    {% if model == None %}
        {{ raise("The model argument can't be None when setting action URLs.") }}
    {% endif %}
    {% with url_params = {} -%}
        {%- do url_params.update(request.view_args if not endpoint else {}),
            url_params.update(request.args if not endpoint else {}) -%}
        {% with record = model.query.get(pk) %}
            {% for url_parameter, db_field in url_tuples %}
                {% if db_field.startswith(':') and '.' in db_field %}
                    {%- set db_field = db_field[1:].split('.') -%}
                    {%- do url_params.update({url_parameter: record[db_field[0]][db_field[1]]}) -%}
                {% elif db_field.startswith(':') %}
                    {%- set db_field = db_field[1:] -%}
                    {%- do url_params.update({url_parameter: record[db_field]}) -%}
                {% else %}
                    {%- do url_params.update({url_parameter: db_field}) -%}
                {% endif %}
            {% endfor %}
        {% endwith -%}
        {{ arg_url_for(endpoint, url_params) }}
    {%- endwith %}
{%- endmacro %}

{% macro render_ui_table(data,
                      titles=None,
                      primary_key='id',
                      primary_key_title='#',
                      caption=None,
                      caption_class=None,
                      caption_icon=None,
                      table_classes=None,
                      header_classes=None,
                      responsive=False,
                      responsive_class=None,
                      stackable_class=None,
                      model=None,
                      show_actions=False,
                      actions_title='Actions',
                      custom_actions=None,
                      view_url=None,
                      edit_url=None,
                      delete_url=None,
                      new_url=None,
                      action_pk_placeholder=':id') %}
{% if not titles %}
    {% set titles = get_table_titles(data, primary_key, primary_key_title) %}
{% endif %}
{% if responsive %}
    <div class="ui {{ responsive_class }}">
{% endif %}
<table class="ui{% if stackable_class in [stackable, unstackable] %} {{stackable_class}}{% endif %} celled table{% if table_classes %}{{ ' ' + table_classes }}{% endif %}">
    {% if caption %}
    <div{% if caption_class %} class="{{ caption_class }}"{% endif %}>
        {% if caption_icon %}<i class="{{caption_icon}} icon"></i>{% endif %}{{ caption }}
    </div>
    {% endif %}
    <thead{% if header_classes %} class="{{ header_classes }}"{% endif %}>
    <tr>
    {% for title in titles %}<th>{{ title[1] }}</th>{% endfor %}
    {% if show_actions %}
        <th scope="col">{{ actions_title }}
        {% if new_url %}
            <a class="ui item"
                {% if new_url.startswith('/') %}
                    href="{{ new_url }}"
                {% else %}
                    href="{{ url_for(new_url) }}"
                {% endif %}
                title="{{ config['FOMANTIC_TABLE_NEW_TITLE'] }}">
                {{ render_ui_icon('plus') }}
            </a>
        {% endif %}
        </th>
    {% endif %}
    </tr>
    </thead>
    <tbody>
    {% for row in data %}
    <tr>
        {% for title in titles %}
        {% if title[0] == primary_key %}
            <td data-label="{{ title[1] }}">{{ row[title[0]] }}</td>
        {% else %}
            <td>{{ row[title[0]] }}</td>
        {% endif %}
        {% endfor %}
        {% if show_actions %}
        <td>
            {% if custom_actions %}
            {% for (action_name, action_icon, action_url) in custom_actions %}
                <a class="ui item"
                   {% if action_url is string %}
                    href="{{ action_url }}"
                   {% else %}
                    href="{{ build_url(action_url[0], model, row[primary_key], action_url[1]) | trim }}"
                   {% endif %}
                    title="{{ action_name }}">{{ render_ui_icon(action_icon) }}</a>
            {% endfor %}
            {% endif %}
            {% if view_url %}
                <a class="ui item"
                   {% if view_url is string %}
                    href="{{ view_url }}"
                   {% else %}
                    href="{{ build_url(view_url[0], model, row[primary_key], view_url[1]) | trim }}"
                   {% endif %}
                    title="{{ config['FOMANTIC_TABLE_VIEW_TITLE'] }}">
                    {{ render_ui_icon('eye') }}
                </a>
            {% endif %}
            {% if edit_url -%}
                <a class="ui item"
                   {% if edit_url is string %}
                    href="{{ edit_url }}"
                   {% else %}
                    href="{{ build_url(edit_url[0], model, row[primary_key], edit_url[1]) | trim }}"
                   {% endif %}
                    title="{{ config['FOMANTIC_TABLE_EDIT_TITLE'] }}">
                    {{ render_ui_icon('pencil', 'green') }}
                </a>
            {%- endif %}
            {% if delete_url %}
            <form style="display:inline"
                  {% if delete_url is string %}
                   action="{{ delete_url }}"
                  {% else %}
                   action="{{ build_url(delete_url[0], model, row[primary_key], delete_url[1]) | trim }}"
                  {% endif %}
                   method="post">
                  {% if csrf_token is undefined %}
                  {{ raise('You have to enable the CSRFProtect extension from Flask-WTF to use delete_url, see the docs for more details (https://bootstrap-flask.readthedocs.io/en/stable/macros.html#render-table).') }}
                  {% endif %}
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
                <a class="ui item"
                    href="javascript:{}"
                    onclick="this.closest('form').submit();return false;"
                    title="{{ config['FOMANTIC_TABLE_DELETE_TITLE'] }}">
                    {{ render_ui_icon('trash', 'red') }}
                </a>
            </form>
            {% endif %}
        </td>
        {% endif %}
    </tr>
    {% endfor %}
    </tbody>
</table>
{% if responsive %}
    </div>
{% endif %}
{% endmacro %}