{% extends 'structures/base.html' %}
{% load i18n %}
{% load bootstrap %}
{% load static %}
{% load humanize %}

{% block details %}

    <span class="pull-right">
        {% if perms.structures.add_structure_owner %}
            <a class="btn btn-success btn-tabs" href="{% url 'structures:add_structure_owner' %}" title="{% translate 'Add new structure owner or add new sync character to an existing structure owner' %}">
                {% translate "Add Owner / Sync Character" %}
            </a>
        {% endif %}
    </span>

    <!-- Nav tabs -->
    <ul id="structure-tabs" class="nav nav-tabs" role="tablist">
        {% if perms.structures.view_corporation_structures or perms.structures.view_alliance_structures or perms.structures.view_all_structures %}
            <li role="presentation"><a href="#structures" aria-controls="structures" role="tab" data-toggle="tab">{% trans "All Structures" %}</a></li>
            {% if show_jump_gates_tab %}
                <li role="presentation"><a href="#jump-gates" aria-controls="jump-gates" role="tab" data-toggle="tab">{% trans "Jump Gates" %}</a></li>
            {% endif %}
            <li role="presentation"><a href="#summary" aria-controls="summary" role="tab" data-toggle="tab">{% trans "Summary" %}</a></li>
            <script id="active-tab" type="application/javascript">
                let activeTab = 'structures';
            </script>
        {% else%}
            <script id="active-tab" type="application/javascript">
                let activeTab = 'pocos';
            </script>
        {% endif %}
        <li role="presentation"><a href="#pocos" aria-controls="pocos" role="tab" data-toggle="tab">{% translate "Customs Offices" %}</a></li>
    </ul>

    <div class="panel panel-default panel-tabs">
        <div class="panel-body">
            <div class="tab-content">
                {% if perms.structures.view_corporation_structures or perms.structures.view_alliance_structures or perms.structures.view_all_structures %}
                    {% include "structures/partials/structure_list.html" %}
                    {% if show_jump_gates_tab %}
                        {% include "structures/partials/jump_gates_list.html" %}
                    {% endif %}
                    {% include "structures/partials/structure_summary.html" %}
                {% endif %}
                {% include "structures/partials/poco_list.html" %}

                <p class="text-muted">
                    {% translate "All dates are EVE time" %}
                    • {% translate "Data can be outdated by up to 1 hour due to API caching." %}
                    • {% translate "Last updated" %} {{ last_updated|naturaltime|default:"?" }}
                </p>

            </div>
        </div>
    </div>
{% endblock %}

{% block extra_javascript %}
    {% include 'bundles/datatables-js.html' %}
    <script type="application/javascript" src="{% static 'js/filterDropDown/filterDropDown.min.js' %}"></script>
    <script type="application/javascript">
        $(document).ready(function () {
            var dataTablesPageLength = {{ data_tables_page_length }};
            var dataTablesPaging = ("{{ data_tables_paging }}" == 'True');

            // sum numbers in column and write result in footer row
            // Args:
            // - api: current api object
            // - columnIdx: Index number of columns to sum, starts with 0
            // - format: format of output. either 'number' or 'isk'
            function dataTableFooterSumColumn(api, columnIdx) {
                // Remove the formatting to get integer data for summation
                const intVal = function (i) {
                    return typeof i === 'string' ?
                        i.replace(/[\$,]/g, '') * 1 :
                        typeof i === 'number' ?
                            i : 0;
                };

                const columnTotal = api
                    .column(columnIdx)
                    .data()
                    .reduce(function (a, b) {
                            return intVal(a) + intVal(b);
                        },
                        0
                    );
                $(api.column(columnIdx).footer()).html(
                    columnTotal.toLocaleString('en-US', {maximumFractionDigits: 0})
                );
            }

            /* structures */
            $('#tab_structures').DataTable({
                ajax: {
                    url: "{% url 'structures:structure_list_data' %}?tags={{ active_tags|join:',' }}",
                    dataSrc: 'data',
                    cache: false
                },
                columns: [
                    { data: 'corporation_icon' },
                    { data: 'owner' },
                    { data: 'location' },
                    { data: 'type_icon' },
                    { data: 'type' },
                    { data: 'structure_name' },
                    { data: 'services' },
                    {
                        data: 'last_online_at',
                        render: {
                            _: 'display',
                            sort: 'timestamp'
                        }
                    },
                    {
                        data: 'fuel_expires_at',
                        render: {
                            _: 'display',
                            sort: 'timestamp'
                        }
                    },
                    { data: 'reinforcement' },
                    { data: 'state_details' },
                    { data: 'core_status' },
                    { data: 'details' },
                    /* hidden */
                    { data: 'alliance_name' },
                    { data: 'corporation_name' },
                    { data: 'region_name' },
                    { data: 'solar_system_name' },
                    { data: 'category_name' },
                    { data: 'group_name' },
                    { data: 'is_reinforced_str' },
                    { data: 'state_str' },
                    { data: 'power_mode_str' },
                    { data: 'core_status_str' }
                ],
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                paging: dataTablesPaging,
                pageLength: dataTablesPageLength,
                columnDefs: [
                    { "sortable": false, "targets": [0, 3, 4, 6, 12] },
                    { "visible": false, "targets": [13, 14, 15, 16, 17, 18, 19, 20, 21, 22] }
                ],
                order: [[1, "asc"], [5, "asc"]],
                filterDropDown:
                {
                    columns: [
                        {
                            idx: 13,
                            title: "{% translate 'Alliance' %}",
                            maxWidth: "11em"
                        },
                        {
                            idx: 14,
                            title: "{% translate 'Corporation' %}",
                            maxWidth: "11em"
                        },
                        {
                            idx: 15,
                            title: "{% translate 'Region' %}",
                            maxWidth: "7em"
                        },
                        {
                            idx: 16,
                            title: "{% translate 'Solar System' %}",
                            maxWidth: "14em"
                        },
                        {
                            idx: 17,
                            title: "{% translate 'Category' %}",
                            maxWidth: "10em"
                        },
                        {
                            idx: 18,
                            title: "{% translate 'Group' %}",
                            maxWidth: "7em"
                        },
                        {
                            idx: 19,
                            title: "{% translate 'Reinforced?' %}",
                            maxWidth: "13em"
                        },
                        {
                            idx: 20,
                            title: "{% translate 'State' %}",
                            maxWidth: "6em"
                        },
                        {
                            idx: 21,
                            title: "{% translate 'Power Mode' %}",
                            maxWidth: "12em"
                        },
                        {
                            idx: 22,
                            title: "{% translate 'Core?' %}",
                            maxWidth: "6em"
                        }
                    ],
                    autoSize: false,
                    bootstrap: true
                },
                createdRow: function (row, data, dataIndex) {
                    if (data['is_reinforced']) {
                        $(row).addClass('danger');
                    }
                }
            });

            $('#modalUpwellDetails').on('show.bs.modal', function(event) {
                $(this).find('.modal-title').html('Loading...');
                {% if NIGHT_MODE %}
                    $(this).find('.modal-body').html('<img src="{% static "structures/img/Spinner-1s-64px-dark.gif" %}">');
                {% else %}
                    $(this).find('.modal-body').html('<img src="{% static "structures/img/Spinner-1s-64px-light.gif" %}">');
                {% endif %}

                const button = $(event.relatedTarget);
                const ajax_url = button.data('ajax_url');
                $("#modalUpwellDetailsContent").load(
                    ajax_url, null, (response, status, xhr) => {
                        if (status != 'success') {
                            $(this).find('.modal-title').html('Error');
                            $(this).find('.modal-body').html(
                                `<p class="text-danger">${xhr.status} ${xhr.statusText}</p>`
                            );
                        }
                    }
                );
            });

            $('#modalPocoDetails').on('show.bs.modal', function(event) {
                $(this).find('.modal-title').html('Loading...');
                {% if NIGHT_MODE %}
                    $(this).find('.modal-body').html('<img src="{% static "structures/img/Spinner-1s-64px-dark.gif" %}">');
                {% else %}
                    $(this).find('.modal-body').html('<img src="{% static "structures/img/Spinner-1s-64px-light.gif" %}">');
                {% endif %}

                const button = $(event.relatedTarget);
                const ajax_url = button.data('ajax_url');
                $("#modalPocoDetailsContent").load(
                    ajax_url, null, (response, status, xhr) => {
                        if (status != 'success') {
                            $(this).find('.modal-title').html('Error');
                            $(this).find('.modal-body').html(
                                `<p class="text-danger">${xhr.status} ${xhr.statusText}</p>`
                            );
                        }
                    }
                );
            });

            /* pocos */
            $('#tab_pocos').DataTable({
                ajax: {
                    url: "{% url 'structures:poco_list_data' %}",
                    dataSrc: 'data',
                    cache: false
                },
                columns: [
                    { data: 'type_icon' },
                    { data: 'region' },
                    {
                        data: 'solar_system_html',
                        render: {
                            _: 'display',
                            sort: 'sort'
                        }
                    },
                    { data: 'planet' },
                    { data: 'planet_type_icon' },
                    { data: 'planet_type_name' },
                    { data: 'has_access_html' },
                    { data: 'tax' },
                    /* hidden columns */
                    { data: 'solar_system' },
                    { data: 'space_type' },
                    { data: 'has_access_str' },
                ],
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                paging: dataTablesPaging,
                pageLength: dataTablesPageLength,
                columnDefs: [
                    { "sortable": false, "targets": [0, 4] },
                    { "visible": false, "targets": [ 8, 9, 10 ] },
                ],
                order: [ [1, "asc"], [3, "asc"] ],
                filterDropDown:
                {
                    columns: [
                        {
                            idx: 9,
                            title: "{% translate 'Space Type' %}"
                        },
                        {
                            idx: 1
                        },
                        {
                            idx: 8,
                            title: "{% translate 'Solar System' %}"
                        },
                        {
                            idx: 5
                        },
                        {
                            idx: 10,
                            title: "{% translate 'Access?' %}"
                        },
                    ],
                    autoSize: false,
                    bootstrap: true
                }
            });

            /* pocos */
            $('#tab_summary').DataTable({
                ajax: {
                    url: "{% url 'structures:structure_summary_data' %}",
                    dataSrc: 'data',
                    cache: false
                },
                columns: [
                    { data: 'corporation_icon' },
                    { data: 'corporation_name' },
                    { data: 'alliance_name' },
                    {
                        data: 'citadel_count',
                        render: $.fn.dataTable.render.number(',', '.', 0)
                    },
                    {
                        data: 'ec_count',
                        render: $.fn.dataTable.render.number(',', '.', 0)
                    },
                    {
                        data: 'refinery_count',
                        render: $.fn.dataTable.render.number(',', '.', 0)
                    },
                    {
                        data: 'other_count',
                        render: $.fn.dataTable.render.number(',', '.', 0)
                    },
                    {
                        data: 'poco_count',
                        render: $.fn.dataTable.render.number(',', '.', 0)
                    },
                    {
                        data: 'starbase_count',
                        render: $.fn.dataTable.render.number(',', '.', 0)
                    },
                    {
                        data: 'total',
                        render: $.fn.dataTable.render.number(',', '.', 0)
                    },
                ],
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                paging: dataTablesPaging,
                pageLength: dataTablesPageLength,
                order: [ [ 1, "asc" ] ],
                columnDefs: [
                    { "sortable": false, "targets": [ 0 ] },
                ],
                filterDropDown:
                {
                    columns: [
                        {
                            idx: 2

                        }
                    ],
                    autoSize: false,
                    bootstrap: true
                },
                footerCallback: function (row, data, start, end, display) {
                    var api = this.api(), data;

                    dataTableFooterSumColumn(api, 3);
                    dataTableFooterSumColumn(api, 4);
                    dataTableFooterSumColumn(api, 5);
                    dataTableFooterSumColumn(api, 6);
                    dataTableFooterSumColumn(api, 7);
                    dataTableFooterSumColumn(api, 8);
                    dataTableFooterSumColumn(api, 9);
                }
            });

            /* jump gates */
            $('#tab_jump_gates').DataTable({
                ajax: {
                    url: "{% url 'structures:jump_gates_list_data' %}",
                    dataSrc: 'data',
                    cache: false
                },
                columns: [
                    { data: 'corporation_icon' },
                    { data: 'owner' },
                    { data: 'location' },
                    { data: 'structure_name' },
                    {
                        data: 'last_online_at',
                        render: {
                            _: 'display',
                            sort: 'timestamp'
                        }
                    },
                    {
                        data: 'fuel_expires_at',
                        render: {
                            _: 'display',
                            sort: 'timestamp'
                        }
                    },
                    {
                        data: 'jump_fuel_quantity',
                        render: $.fn.dataTable.render.number(',', '.', 0)
                    },
                    /* hidden */
                    { data: 'alliance_name' },
                    { data: 'corporation_name' },
                    { data: 'region_name' },
                    { data: 'solar_system_name' },
                    { data: 'is_reinforced_str' },
                    { data: 'power_mode_str' },
                ],
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                paging: dataTablesPaging,
                pageLength: dataTablesPageLength,
                order: [[1, "asc"]],
                columnDefs: [
                    { "sortable": false, "targets": [ 0, 2 ] },
                    { "visible": false, "targets": [ 7, 8, 9, 10, 11, 12 ] },
                ],
                filterDropDown:
                {
                   columns: [
                        {
                            idx: 7,
                            title: "{% translate 'Alliance' %}",
                            maxWidth: "11em"
                        },
                        {
                            idx: 8,
                            title: "{% translate 'Corporation' %}",
                            maxWidth: "11em"
                        },
                        {
                            idx: 9,
                            title: "{% translate 'Region' %}",
                            maxWidth: "7em"
                        },
                        {
                            idx: 10,
                            title: "{% translate 'Solar System' %}",
                            maxWidth: "14em"
                        },
                        {
                            idx: 11,
                            title: "{% translate 'Reinforced?' %}",
                            maxWidth: "13em"
                        },
                        {
                            idx: 12,
                            title: "{% translate 'Power Mode' %}",
                            maxWidth: "12em"
                        }
                    ],
                    autoSize: false,
                    bootstrap: true
                },
                createdRow: function (row, data, dataIndex) {
                    if (data['is_reinforced']) {
                        $(row).addClass('danger');
                    }
                },
            });


            $('#structure-tabs a[href="#' + activeTab + '"]').tab('show')

        });
    </script>
{% endblock %}

{% block extra_css %}
    {% include 'bundles/datatables-css.html' %}

    <link rel="stylesheet" href="{% static 'structures/css/global.css' %}" type="text/css" media="screen">
    <link rel="stylesheet" href="{% static 'structures/css/main.css' %}" type="text/css" media="screen">
{% endblock %}

{% block extra_script %}

{% endblock %}
