{% load i18n %}
{% load static %}
{% load inventree_extras %}

// Javascript for Pricing panel
onPanelLoad('pricing', function() {
    $('#btn-update-rates').click(function() {
        inventreePut(
            '{% url "api-currency-refresh" %}',
            {},
            {
                method: 'POST',
                success: function(data) {
                    location.reload();
                }
            }
        );
    });

    $('#exchange-rate-table').inventreeTable({
        url: '{% url "api-currency-exchange" %}',
        search: false,
        showColumns: false,
        sortable: true,
        sidePagination: 'client',
        onLoadSuccess: function(response) {
            var data = response.exchange_rates || {};

            var rows = [];

            for (var currency in data) {
                rows.push({
                    'currency': currency,
                    'rate': data[currency],
                });
            }

            $('#exchange-rate-table').bootstrapTable('load', rows);
        },
        columns: [
            {
                field: 'currency',
                sortable: true,
                title: '{% trans "Currency" escape %}',
            },
            {
                field: 'rate',
                sortable: true,
                title: '{% trans "Rate" escape %}',
            }
        ]
    });
});

// Javascript for units panel
onPanelLoad('units', function() {

    console.log("units panel");

    // Construct the "units" table
    $('#physical-units-table').bootstrapTable({
        url: '{% url "api-custom-unit-list" %}',
        search: true,
        columns: [
            {
                field: 'name',
                title: '{% trans "Name" escape %}',
            },
            {
                field: 'definition',
                title: '{% trans "Definition" escape %}',
            },
            {
                field: 'symbol',
                title: '{% trans "Symbol" escape %}',
                formatter: function(value, row) {
                    let html = value;
                    let buttons = '';

                    buttons += makeEditButton('button-units-edit', row.pk, '{% trans "Edit" escape %}');
                    buttons += makeDeleteButton('button-units-delete', row.pk, '{% trans "Delete" escape %}');

                    html += wrapButtons(buttons);
                    return html;
                }
            },
        ]
    });

    // Callback to edit a custom unit
    $('#physical-units-table').on('click', '.button-units-edit', function() {
        let pk = $(this).attr('pk');

        constructForm(`{% url "api-custom-unit-list" %}${pk}/`, {
            title: '{% trans "Edit Custom Unit" escape %}',
            fields: {
                name: {},
                definition: {},
                symbol: {},
            },
            refreshTable: '#physical-units-table',
        });
    });

    // Callback to delete a custom unit
    $('#physical-units-table').on('click', '.button-units-delete', function() {
        let pk = $(this).attr('pk');

        constructForm(`{% url "api-custom-unit-list" %}${pk}/`, {
            title: '{% trans "Delete Custom Unit" escape %}',
            method: 'DELETE',
            refreshTable: '#physical-units-table',
        });
    });

    // Callback to create a new custom unit
    $('#custom-unit-create').click(function() {
        constructForm('{% url "api-custom-unit-list" %}', {
            fields: {
                name: {},
                definition: {},
                symbol: {},
            },
            title: '{% trans "New Custom Unit" escape %}',
            method: 'POST',
            refreshTable: '#physical-units-table',
        });
    });
});

// Javascript for project codes panel
onPanelLoad('project-codes', function() {

    // Construct the project code table
    $('#project-code-table').bootstrapTable({
        url: '{% url "api-project-code-list" %}',
        search: true,
        sortable: true,
        formatNoMatches: function() {
            return '{% trans "No project codes found" escape %}';
        },
        columns: [
            {
                field: 'code',
                sortable: true,
                title: '{% trans "Project Code" escape %}',
            },
            {
                field: 'responsible',
                title: '{% trans "Responsible" escape %}',
                formatter: function(value, row) {
                    if (!row.responsible_detail) {
                        return '-';
                    }

                    var html = row.responsible_detail.name;

                    if (row.responsible_detail.label == '{% trans "group" escape %}') {
                        html += `<span class='float-right fas fa-users'></span>`;
                    } else {
                        html += `<span class='float-right fas fa-user'></span>`;
                    }

                    return html;
                }
            },
            {
                field: 'description',
                sortable: false,
                title: '{% trans "Description" escape %}',
                formatter: function(value, row) {
                    let html = value;
                    let buttons = '';

                    buttons += makeEditButton('button-project-code-edit', row.pk, '{% trans "Edit Project Code" escape %}');
                    buttons += makeDeleteButton('button-project-code-delete', row.pk, '{% trans "Delete Project Code" escape %}');

                    html += wrapButtons(buttons);
                    return html;
                }
            }
        ]
    });

    $('#project-code-table').on('click', '.button-project-code-edit', function() {
        let pk = $(this).attr('pk');

        constructForm(`{% url "api-project-code-list" %}${pk}/`, {
            title: '{% trans "Edit Project Code" escape %}',
            fields: {
                code: {},
                description: {},
                responsible: {},
            },
            refreshTable: '#project-code-table',
        });
    });

    $('#project-code-table').on('click', '.button-project-code-delete', function() {
        let pk = $(this).attr('pk');

        constructForm(`{% url "api-project-code-list" %}${pk}/`, {
            title: '{% trans "Delete Project Code" escape %}',
            method: 'DELETE',
            refreshTable: '#project-code-table',
        });
    });

    $('#new-project-code').click(function() {
        // Construct a new project code
        constructForm('{% url "api-project-code-list" %}', {
            fields: {
                code: {},
                description: {},
            },
            title: '{% trans "New Project Code" escape %}',
            method: 'POST',
            refreshTable: '#project-code-table',
        });
    })
});

// Javascript for Part Category panel
onPanelLoad('category', function() {
    $('#category-select').select2({
        placeholder: '',
        width: '100%',
        ajax: {
            url: '{% url "api-part-category-list" %}',
            dataType: 'json',
            delay: 250,
            cache: false,
            data: function(params) {
                if (!params.page) {
                    offset = 0;
                } else {
                    offset = (params.page - 1) * 25;
                }

                return {
                    search: params.term,
                    offset: offset,
                    limit: 25,
                };
            },
            processResults: function(response) {
                var data = [];

                var more = false;

                if ('count' in response && 'results' in response) {
                    // Response is paginated
                    data = response.results;

                    // Any more data available?
                    if (response.next) {
                        more = true;
                    }

                } else {
                    // Non-paginated response
                    data = response;
                }

                // Each 'row' must have the 'id' attribute
                for (var idx = 0; idx < data.length; idx++) {
                    data[idx].id = data[idx].pk;
                    data[idx].text = data[idx].pathstring;
                }

                // Ref: https://select2.org/data-sources/formats
                var results = {
                    results: data,
                    pagination: {
                        more: more,
                    }
                };

                return results;
            }
        },
    });

    $('#cat-param-table').inventreeTable({
        formatNoMatches: function() { return '{% trans "No category parameter templates found" escape %}'; },
        columns: [
            {
                field: 'pk',
                title: 'ID',
                visible: false,
                switchable: false,
            },
            {
                field: 'parameter_template_detail.name',
                title: '{% trans "Parameter Template" escape %}',
                sortable: 'true',
            },
            {
                field: 'category_detail.pathstring',
                title: '{% trans "Category" escape %}',
            },
            {
                field: 'default_value',
                title: '{% trans "Default Value" escape %}',
                sortable: 'true',
                formatter: function(value, row, index, field) {
                    let buttons = '';
                    buttons += makeEditButton('template-edit', row.pk, '{% trans "Edit Template" escape %}');
                    buttons += makeDeleteButton('template-delete', row.pk, '{% trans "Delete Template" escape %}');

                    let html = value
                    html += wrapButtons(buttons);

                    return html;
                }
            }
        ]
    });

    $("#cat-param-table").on('click', '.template-edit', function() {

        var category = $('#category-select').val();
        var pk = $(this).attr('pk');

        constructForm(`/api/part/category/parameters/${pk}/`, {
            title: '{% trans "Edit Category Parameter Template" escape %}',
            fields: {
                parameter_template: {},
                category: {
                    icon: 'fa-sitemap',
                    tree_picker: {
                        url: '{% url "api-part-category-tree" %}',
                        default_icon: global_settings.PART_CATEGORY_DEFAULT_ICON,
                    },
                },
                default_value: {},
            },
            onSuccess: function() {
                loadTemplateTable(pk);
            }
        });
    });

    $("#cat-param-table").on('click', '.template-delete', function() {

        var category = $('#category-select').val();
        var pk = $(this).attr('pk');

        var url = `/part/category/${category}/parameters/${pk}/delete/`;

        constructForm(`/api/part/category/parameters/${pk}/`, {
            method: 'DELETE',
            title: '{% trans "Delete Category Parameter Template" escape %}',
            onSuccess: function() {
                loadTemplateTable(pk);
            }
        });
    });

    function loadTemplateTable(pk) {

        var query = {};

        if (pk) {
            query['category'] = pk;
        }

        // Load the parameter table
        $("#cat-param-table").bootstrapTable('refresh', {
            query: query,
            url: '{% url "api-part-category-parameter-list" %}',
        });
    }

    // Initially load table with *all* categories
    loadTemplateTable();

    $('body').on('change', '#category-select', function() {
        var pk = $(this).val();
        loadTemplateTable(pk);
    });

    $("#new-cat-param").click(function() {

        var pk = $('#category-select').val();

        constructForm('{% url "api-part-category-parameter-list" %}', {
            title: '{% trans "Create Category Parameter Template" escape %}',
            method: 'POST',
            fields: {
                parameter_template: {},
                category: {
                    icon: 'fa-sitemap',
                    value: pk,
                    tree_picker: {
                        url: '{% url "api-part-category-tree" %}',
                        default_icon: global_settings.PART_CATEGORY_DEFAULT_ICON,
                    },
                },
                default_value: {},
            },
            onSuccess: function() {
                loadTemplateTable(pk);
            }
        });
    });
});

// Javascript for the Part parameters settings panel
onPanelLoad('part-parameters', function() {

    loadPartParameterTemplateTable("#param-table", {});

    $("#new-param").click(function() {
        constructForm('{% url "api-part-parameter-template-list" %}', {
            fields: partParameterTemplateFields(),
            method: 'POST',
            title: '{% trans "Create Part Parameter Template" escape %}',
            refreshTable: '#param-table',
        });
    });
});

// Javascript for the Part settings panel
onPanelLoad('parts', function() {
    $("#import-part").click(function() {
        launchModalForm("{% url 'api-part-import' %}?reset", {});
    });
});

// Javascript for the Stock settings panel
onPanelLoad("stock", function() {

    // Construct the stock location type table
    $('#location-type-table').bootstrapTable({
        url: '{% url "api-location-type-list" %}',
        search: true,
        sortable: true,
        formatNoMatches: function() {
            return '{% trans "No stock location types found" escape %}';
        },
        columns: [
            {
                field: 'name',
                sortable: true,
                title: '{% trans "Name" escape %}',
            },
            {
                field: 'description',
                sortable: false,
                title: '{% trans "Description" escape %}',
            },
            {
                field: 'icon',
                sortable: true,
                title: '{% trans "Icon" escape %}',
            },
            {
                field: 'location_count',
                sortable: true,
                title: '{% trans "Location count" escape %}',
                formatter: function(value, row) {
                    let html = value;
                    let buttons = '';

                    buttons += makeEditButton('button-location-type-edit', row.pk, '{% trans "Edit Location Type" escape %}');
                    buttons += makeDeleteButton('button-location-type-delete', row.pk, '{% trans "Delete Location type" escape %}');

                    html += wrapButtons(buttons);
                    return html;
                }
            }
        ]
    });

    $('#location-type-table').on('click', '.button-location-type-edit', function() {
        let pk = $(this).attr('pk');

        constructForm(`{% url "api-location-type-list" %}${pk}/`, {
            title: '{% trans "Edit Location Type" escape %}',
            fields: stockLocationTypeFields(),
            refreshTable: '#location-type-table',
        });
    });

    $('#location-type-table').on('click', '.button-location-type-delete', function() {
        let pk = $(this).attr('pk');

        constructForm(`{% url "api-location-type-list" %}${pk}/`, {
            title: '{% trans "Delete Location Type" escape %}',
            method: 'DELETE',
            refreshTable: '#location-type-table',
        });
    });

    $('#new-location-type').click(function() {
        // Construct a new location type
        constructForm('{% url "api-location-type-list" %}', {
            fields: stockLocationTypeFields(),
            title: '{% trans "New Location Type" escape %}',
            method: 'POST',
            refreshTable: '#location-type-table',
        });
    });
});

// Javascript for the Stocktake settings panel
onPanelLoad('stocktake', function() {

    {% if roles.stocktake.view %}
    var table = '#stocktake-report-table';

    var filters = loadTableFilters('stocktakereport');
    setupFilterList('stocktakereport', $(table), '#filter-list-stocktakereport');

    $(table).inventreeTable({
        url: '{% url "api-part-stocktake-report-list" %}',
        search: false,
        queryParams: filters,
        name: 'stocktakereport',
        showColumns: false,
        sidePagination: 'server',
        sortable: true,
        sortName: 'date',
        sortOrder: 'desc',
        columns: [
            {
                field: 'report',
                title: '{% trans "Report" escape %}',
                formatter: function(value, row) {
                    return attachmentLink(value);
                }
            },
            {
                field: 'part_count',
                title: '{% trans "Part Count" escape %}',
            },
            {
                field: 'date',
                title: '{% trans "Date" escape %}',
                sortable: true,
                formatter: function(value, row) {
                    let html = renderDate(value);

                    if (row.user_detail) {
                        html += `<span class='badge bg-dark rounded-pill float-right'>${row.user_detail.username}</span>`;
                    }

                    return html;
                }
            },
        ]
    });
    {% endif %}

    {% if roles.stocktake.add %}
    $('#btn-generate-stocktake').click(function() {
        generateStocktakeReport({
            part: {},
            category: {
                tree_picker: {
                    url: '{% url "api-part-category-tree" %}',
                    default_icon: global_settings.PART_CATEGORY_DEFAULT_ICON,
                },
            },
            location: {
                tree_picker: {
                    url: '{% url "api-location-tree" %}',
                    default_icon: global_settings.STOCK_LOCATION_DEFAULT_ICON,
                },
            },
            generate_report: {},
            update_parts: {},
        });
    });
    {% endif %}
});

// Javascript for plugins panel
onPanelLoad('plugin', function() {

{% plugins_enabled as plug %}

    loadPluginTable('#plugin-table', {
        custom: {% js_bool plug %},
    });

{% if plug %}
    // Callback to install new plugin
    $("#install-plugin").click(function() {
        installPlugin();
    });

    // Callback to reload plugins
    $('#reload-plugins').click(function() {
        reloadPlugins();
    });

{% endif %}
});
