{% extends "allianceauth/base-bs5.html" %}
{% load aa_i18n %}

{% load i18n %}
{% load humanize %}

{% block page_title %}
    {% translate "SRP Fleet Data" %}
{% endblock page_title %}

{% block header_nav_brand %}
    {% translate "Ship Replacement Program" %}
{% endblock header_nav_brand %}

{% block header_nav_collapse_left %}
    <a class="nav-link" href="{% url 'srp:management' %}">
        {% translate "View Fleets" %}
    </a>
{% endblock header_nav_collapse_left %}

{% block header_nav_collapse_right %}
    {% if perms.auth.srp_management %}
        {% if fleet_status == "Completed" %}
            {% translate "Mark Incomplete" as nav_item_title %}
            {% url "srp:mark_uncompleted" fleet_id as nav_item_link %}
            {% include "framework/header/nav-collapse-button.html" with btn_modifier="warning" url=nav_item_link title=nav_item_title %}
        {% else %}
            {% translate "Mark Completed" as nav_item_title %}
            {% url "srp:mark_completed" fleet_id as nav_item_link %}
            {% include "framework/header/nav-collapse-button.html" with btn_modifier="warning" url=nav_item_link title=nav_item_title %}
        {% endif %}
    {% endif %}
{% endblock header_nav_collapse_right %}

{% block content %}
    <div>
        {% translate "SRP Fleet Data" as page_header %}
        {% include "framework/header/page-header.html" with title=page_header %}

        {% if srpfleetrequests %}
            <form method="POST">
                {% csrf_token %}

                <div class="alert alert-info" role="alert">
                    <div class="text-end">
                        <b><span style="padding-right:2.5em">{% translate "Total Losses:" %} {{ srpfleetrequests.count }}</span></b>
                        <b><span style="padding-right:2.5em">{% translate "Total ISK Cost:" %} {{ totalcost | intcomma }}</span></b>

                        {% if perms.auth.srp_management %}
                            <button type="submit" title="Approve" class="btn btn-success btn-sm m-1" formaction="{% url 'srp:request_approve' %}">
                                <i class="fa-solid fa-thumbs-up"></i>
                            </button>

                            <button type="submit" title="Reject" class="btn btn-warning btn-sm m-1" formaction="{% url 'srp:request_reject' %}">
                                <i class="fa-solid fa-thumbs-down"></i>
                            </button>

                            <button type="submit" title="Remove" onclick="return confirm('{% translate "Are you sure you want to delete SRP requests?" %}')" class="btn btn-danger btn-sm m-1" formaction="{% url 'srp:request_remove' %}">
                                <i class="fa-solid fa-trash-can"></i>
                            </button>
                        {% endif %}
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table srplist">
                        <thead>
                            <th>{% translate "Pilot Name" %}</th>
                            <th>{% translate "Killboard Link" %}</th>
                            <th>{% translate "Additional Info" %}</th>
                            <th>{% translate "Ship Type" %}</th>
                            <th>{% translate "Killboard Loss Amt" %}</th>
                            <th>
                                {% translate "SRP ISK Cost" %}
                                <i class="fa-solid fa-circle-question" rel="tooltip" title="{% blocktranslate trimmed %}Click value to edit
Enter to save & next
ESC to cancel{% endblocktranslate %}" id="blah"></i></th>
                            <th>{% translate "Post Time" %}</th>
                            <th>{% translate "Status" %}</th>
                            {% if perms.auth.srp_management %}
                                <th>{% translate "Actions" %}</th>
                            {% endif %}
                        </thead>

                        <tbody>
                        {% for srpfleetrequest in srpfleetrequests %}
                            <tr>
                                <td>
                                    {% if srpfleetrequest.character.alliance.alliance_ticker %}
                                        {{ srpfleetrequest.character.alliance.alliance_ticker }}
                                    {% endif %}
                                    [{{ srpfleetrequest.character.corporation.corporation_ticker }}]
                                    {{ srpfleetrequest.character.character_name }}&nbsp;
                                    <sup>
                                        <i class="copy-text-fa-icon far fa-copy" data-clipboard-text="{{ srpfleetrequest.character.character_name }}"></i>
                                    </sup>
                                </td>
                                <td>
                                    <a href="{{ srpfleetrequest.killboard_link }}"
                                    target="_blank" class="badge text-bg-warning">{% translate "Link" %}</a>
                                </td>
                                <td>{{ srpfleetrequest.additional_info }}</td>
                                <td>{{ srpfleetrequest.srp_ship_name }}</td>
                                <td class="text-end" data-sort="{{ srpfleetrequest.kb_total_loss }}">{{ srpfleetrequest.kb_total_loss | intcomma }} ISK</td>
                                <td class="srp text-end" data-name="srp_total_amount" data-type="number" data-pk="{{srpfleetrequest.id}}" data-url="{% url 'srp:request_update_amount' srpfleetrequest.id %}" data-params="{csrfmiddlewaretoken:'{{csrf_token}}'}" data-sort="{{ srpfleetrequest.srp_total_amount }}">{{ srpfleetrequest.srp_total_amount | intcomma }} ISK</td>
                                <td data-sort="{{ srpfleetrequest.post_time | date:"Y-m-d H:i" }}">{{ srpfleetrequest.post_time | date:"Y-M-d H:i" }}</td>
                                <td>
                                    {% if srpfleetrequest.srp_status == "Approved" %}
                                        <div class="badge text-bg-success">
                                            {% translate "Approved" %}
                                        </div>
                                    {% elif srpfleetrequest.srp_status == "Rejected" %}
                                        <div class="badge text-bg-danger">
                                            {% translate "Rejected" %}
                                        </div>
                                    {% else %}
                                        <div class="badge text-bg-warning">
                                            {% translate "Pending" %}
                                        </div>
                                    {% endif %}
                                </td>
                                {% if perms.auth.srp_management %}
                                    <td class="text-end">
                                        <div class="checkbox">
                                            <label style="font-size: 1.5em">
                                                <input type="checkbox" name="{{srpfleetrequest.id}}">
                                                <span class="cr"><i class="cr-icon fas fa-check"></i></span>
                                            </label>
                                        </div>
                                    </td>
                                {% endif %}
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>

                <div class="alert alert-info" role="alert">
                    <div class="text-end">
                        <b><span style="padding-right:2.5em">{% translate "Total Losses:" %} {{ srpfleetrequests.count }}</span></b>
                        <b><span style="padding-right:2.5em">{% translate "Total ISK Cost:" %} {{ totalcost | intcomma }}</span></b>

                        {% if perms.auth.srp_management %}
                            <button type="submit" title="Approve" class="btn btn-success btn-sm m-1" formaction="{% url 'srp:request_approve' %}">
                                <i class="fa-solid fa-thumbs-up"></i>
                            </button>

                            <button type="submit" title="Reject" class="btn btn-warning btn-sm m-1" formaction="{% url 'srp:request_reject' %}">
                                <i class="fa-solid fa-thumbs-down"></i>
                            </button>

                            <button type="submit" title="Remove" onclick="return confirm('{% translate "Are you sure you want to delete SRP requests?" %}')" class="btn btn-danger btn-sm m-1" formaction="{% url 'srp:request_remove' %}">
                                <i class="fa-solid fa-trash-can"></i>
                            </button>
                        {% endif %}
                    </div>
                </div>
            </form>
        {% else %}
            <div class="alert alert-warning text-center">
                {% translate "No SRP requests for this fleet." %}
            </div>
        {% endif %}
    </div>
{% endblock content %}

{% block extra_javascript %}
    {% include "bundles/datatables-js-bs5.html" %}
    {% include "bundles/x-editable-js.html" %}
    {% include "bundles/moment-js.html" %}
    {% include "bundles/clipboard-js.html" %}

    {% get_datatables_language_static LANGUAGE_CODE as DT_LANG_PATH %}

    <script>
        const clipboard = new ClipboardJS('.copy-text-fa-icon');

        clipboard.on('success', (e) => {
            console.info('Action:', e.action);
            console.info('Text:', e.text);
            console.info('Trigger:', e.trigger);

            e.clearSelection();
        });

        clipboard.on('error', (e) => {
            console.error('Action:', e.action);
            console.error('Trigger:', e.trigger);
        });

        $(document).ready(() => {
            const elementEditableSrpAmount = $('.srp');
            const elementTableSrpList = $('table.srplist');

            $.fn.editable.defaults.mode = 'inline';
            $.fn.editable.defaults.showbuttons = false;
            $.fn.editable.defaults.highlight = "rgb(170 255 128)";

            $.fn.dataTable.moment = (format, locale) => {
                const types = $.fn.dataTable.ext.type;

                // Add type detection
                types.detect.unshift((d) => {
                    return moment(d, format, locale, true).isValid() ?
                        'moment-' + format :
                        null;
                });

                // Add sorting method - use an integer for the sorting
                types.order[ 'moment-' + format+'-pre' ] = (d) => {
                    return moment(d, format, locale, true).unix();
                };
            };
            $.fn.dataTable.moment('YYYY-MMM-D, HH:mm');

            elementEditableSrpAmount.editable({
                display: (value, response) => {
                    return false;
                },
                success: function(response, newValue) {
                    newValue = parseInt(newValue);
                    const newValueOutput = `${newValue.toLocaleString()} ISK`;

                    $(this).html(`<b>${newValueOutput}</b>`);
                },
                validate: function(value) {
                    if (value === null || value === '') {
                        return 'Empty values not allowed';
                    }
                }
            });

            elementEditableSrpAmount.on('hidden', function(e, reason) {
                if (reason === 'save' || reason === 'nochange') {
                    const next_editable_element = $(this).closest('tr').next().find('.editable');

                    setTimeout(() => {
                        next_editable_element.editable('show');
                    }, 400);
                }
            });

            // Non-Orderable columns
            const nonOrderableTargets = [1];
            {% if perms.auth.srp_management %}
                nonOrderableTargets.push(8);
            {% endif %}

            elementTableSrpList.DataTable({
                language: {url: '{{ DT_LANG_PATH }}'},
                "order": [[ 6, "asc" ]],
                "paging": false,
                "columnDefs": [
                    {
                        "targets": nonOrderableTargets,
                        "orderable": false
                    },
                    {
                        "targets": [4, 5],
                        "type": "num"
                    }
                ],
                "stateSave": true,
                "stateDuration": 0
            });

            // tooltip
            $("[rel=tooltip]").tooltip({ placement: 'top'});
        });
    </script>
{% endblock extra_javascript %}

{% block extra_css %}
    {% include "bundles/datatables-css-bs5.html" %}
    {% include "bundles/x-editable.css.html" %}
    {% include "bundles/checkbox-css.html" %}

    <style>
        .copy-text-fa-icon:hover {
            cursor: pointer;
        }
        .radio label, .checkbox label {
            padding-left: 10px;
        }
        .editable {
            width:150px;
            text-align: center;
        }
        .editableform .form-control {
            width: 95%;
            text-align: center;
            margin-left: 10px;
        }

        .editable-input {
            width: 95%;
        }
        .radio, .checkbox {
            margin-top: 0;
            margin-bottom: 0;
        }
        .editable-error-block {
            white-space: nowrap;
        }
        .editable-click, a.editable-click, a.editable-click:hover {
            border-bottom: none;
        }
        .tooltip-inner {
            white-space:pre;
            max-width: none;
        }
    </style>
{% endblock extra_css %}
