<div id="custom-translation-form" class="pl20 pr20">
    <div id="custom-translation-form-overlay">
        <div>
            <img src="[{$dir_images}]axialis/user-interface/loading2-animation-01.svg" class="animation-rotate mr5" />
            <span>[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]</span>
        </div>
    </div>

    <table class="contentTable mt20 mb20">
        <tr>
            <td class="key">[{isys type="f_label" name="C__CUSTOM_TRANSLATION__NAME" ident="LC__LANGUAGE_LANGUAGE"}]</td>
            <td class="value">[{isys type="f_text" name="C__CUSTOM_TRANSLATION__NAME"}]</td>
        </tr>
        <tr>
            <td class="key">[{isys type="f_label" name="C__CUSTOM_TRANSLATION__ABBREVIATION" ident="LC__LANGUAGE_LANGUAGE_ABBREVIATION"}]</td>
            <td class="value">[{isys type="f_text" name="C__CUSTOM_TRANSLATION__ABBREVIATION"}]</td>
        </tr>
        <tr>
            <td class="key">[{isys type="f_label" name="C__CUSTOM_TRANSLATION__AVAILABLE" ident="LC__LANGUAGE_AVAILABLE"}]</td>
            <td class="value">[{isys type="f_dialog" name="C__CUSTOM_TRANSLATION__AVAILABLE"}]</td>
        </tr>
        <tr>
            <td class="key vat pt5">[{isys type="lang" ident="LC__LANGUAGE_FLAGS"}]</td>
            <td class="value pl20">
                <div class="flag-selection">
                    <ul class="list-style-none m0 p0">
                        [{foreach $flagIcons as $flagIcon}]
                        <li>
                            <label>
                                <input type="radio" name="C__CUSTOM_TRANSLATION__FLAG" value="[{$flagIcon.url}]" [{if $flagIcon.url === $selectedFlagIcon}]checked[{/if}] [{if !$allowedToEdit}]disabled[{/if}] />
                                <img src="[{$dir_images}][{$flagIcon.url}]" title="[{$flagIcon.rawName}]" />
                                <span>[{$flagIcon.name}]</span>
                            </label>
                        </li>
                        [{/foreach}]
                    </ul>
                </div>
            </td>
        </tr>
        <tr>
            <td class="key">[{isys type="lang" ident="LC__LANGUAGE_FLAG_UPLOAD"}]</td>
            <td class="value pl20">[{isys type="f_file_ajax" name="C__CUSTOM_TRANSLATION__FLAG_UPLOAD" uploadType="translation-flag-icon"}]</td>
        </tr>
    </table>

    <div id="custom-translation-table-toolbar">
        [{isys type="f_text" name="custom-translation-table-filter"}]
        <button id="custom-translation-table-filter-process" type="button" class="btn btn-secondary">
            <img src="[{$dir_images}]axialis/imaging/filter.svg" /><span>[{isys type="lang" ident="LC_UNIVERSAL__FILTERS"}]</span>
        </button>
        <button id="custom-translation-table-filter-abort" type="button" class="btn btn-secondary">
            <span>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_RESET"}]</span>
        </button>
    </div>

    <table class="mainTable mainTable-header w100">
        <thead>
        <tr>
            <th>[{isys type="lang" ident="LC__LANGUAGE_CONSTANT"}]</th>
            <th>[{isys type="lang" ident="LC__LANGUAGE_DEFAULT_VALUE"}]</th>
            <th>[{isys type="lang" ident="LC__LANGUAGE_CUSTOM_VALUE"}]</th>
        </tr>
        </thead>
    </table>

    <div id="custom-translation-table-container">
        <table id="custom-translation-table" class="mainTable user-selectable w100">
            <tbody>
            <!-- To be filled by JS -->
            </tbody>
        </table>
    </div>

    <div id="custom-translation-table-pager">
        <span>[{isys type="lang" ident="LC__UNIVERSAL__PAGE"}]</span>
        <button id="custom-translation-table-pager-prev" type="button" title="[{isys type="lang" ident="LC__NAVIGATION__NAVBAR__PREV_TOOLTIP"}]" data-tooltip="1" class="btn btn-secondary">
            <img src="[{$dir_images}]axialis/user-interface/triangle-left.svg" />
        </button>
        <span>[{isys type="f_text" name="custom-translation-table-current-page"}]</span>
        <span> / </span>
        <span class="page-number"> ... </span>
        <button id="custom-translation-table-pager-next" type="button" title="[{isys type="lang" ident="LC__NAVIGATION__NAVBAR__NEXT_TOOLTIP"}]" data-tooltip="1" class="btn btn-secondary">
            <img src="[{$dir_images}]axialis/user-interface/triangle-right.svg" />
        </button>
    </div>
</div>

<style>
    [{include file=$cssPath}]
</style>

<script>
    (function () {
        const $saveButton = $('navbar_item_C__NAVMODE__SAVE');
        const $cancelButton = $('navbar_item_C__NAVMODE__CANCEL');
        const $customTranslationForm = $('custom-translation-form');
        const $customTranslationFormOverlay = $('custom-translation-form-overlay');
        const $customTranslationTable = $('custom-translation-table');
        const $customTranslationTablePager = $('custom-translation-table-pager');
        const abbreviation = '[{$abbreviation}]';

        const $metaName = $('C__CUSTOM_TRANSLATION__NAME');
        const $metaAbbreviation = $('C__CUSTOM_TRANSLATION__ABBREVIATION');
        const $metaAvailable = $('C__CUSTOM_TRANSLATION__AVAILABLE');
        const $metaFlag = $customTranslationForm.down('.flag-selection');

        const $filterInput = $('custom-translation-table-filter');
        const $filterProcess = $('custom-translation-table-filter-process');
        const $filterAbort = $('custom-translation-table-filter-abort');

        const $currentPage = $('custom-translation-table-current-page');

        let currentPage = 0;
        let maxPage = 0;
        let currentFilter = function () { return true; };
        const entriesPerPage = 100;

        $metaFlag.on('change', 'input', function (ev) {
            const $input = ev.findElement('input');
            $metaFlag.select('.selected').invoke('removeClassName', 'selected');
            $input.up('li').addClassName('selected');
        });

        const $selectedFlag = $metaFlag.down(':checked');
        let data = { };

        if ($selectedFlag) {
            $selectedFlag.simulate('change');

            // Scroll to the selected flag.
            $metaFlag.scrollTop = Math.max(0, $selectedFlag.positionedOffset().top - 30);
        }

        if ($saveButton) {
            $saveButton.on('click', function () {
                const translations = { };

                // Collect all changed values.
                data
                    .filter(function(datum) { return datum.changed; })
                    .forEach(function(datum) {
                        translations[datum.key] = datum.custom;
                    });

                const metaData = {
                    title: $metaName.getValue(),
                    abbreviation: $metaAbbreviation.getValue(),
                    icon: '',
                    available: $metaAvailable.getValue()
                };

                $metaName.removeClassName('input-error');
                $metaAbbreviation.removeClassName('input-error');

                if ($metaFlag.down(':checked')) {
                    metaData.icon = $metaFlag.down(':checked').readAttribute('value');
                }

                if (metaData.title.blank()) {
                    idoit.Notify.error('[{isys type="lang" ident="LC__LANGUAGE_LANGUAGE_MANDATORY"}]');
                    $metaName.addClassName('input-error');
                    return;
                }

                if (metaData.abbreviation.blank()) {
                    idoit.Notify.error('[{isys type="lang" ident="LC__LANGUAGE_LANGUAGE_ABBREVIATION_MANDATORY"}]');
                    $metaAbbreviation.addClassName('input-error');
                    return;
                }

                new Ajax.Request(window.www_dir + 'pro/translation/save-custom', {
                    parameters: {
                        abbreviation: abbreviation,
                        meta: JSON.stringify(metaData),
                        translations: JSON.stringify(translations)
                    },
                    method:     'post',
                    onSuccess:  function (xhr) {
                        const json = xhr.responseJSON;

                        if (!is_json_response(xhr, true)) {
                            return;
                        }

                        if (!json.success) {
                            idoit.Notify.error(json.message, { sticky: true });

                            return;
                        }

                        const targetUrl = document.location.href.parseQuery();

                        targetUrl.id = json.data.abbreviation;

                        document.location.href = '?' + Object.toQueryString(targetUrl);
                    }
                });
            });
        }

        if ($cancelButton) {
            $cancelButton.on('click', function () {
                const targetUrl = document.location.href.parseQuery();

                delete targetUrl.id;

                document.location.href = '?' + Object.toQueryString(targetUrl);
            });
        }

        new Ajax.Request(window.www_dir + 'pro/translation/get-custom', {
            parameters: {
                abbreviation: abbreviation
            },
            method:     'get',
            onSuccess:  function (xhr) {
                const json = xhr.responseJSON;

                if (!is_json_response(xhr, true)) {
                    return;
                }

                data = json.data;

                $filterAbort.simulate('click');
            }
        });

        $filterProcess.on('click', function () {
            const query = $filterInput.getValue();

            if (query.blank()) {
                currentFilter = function (row) { return true; };
            } else {
                currentFilter = function (row) {
                    return [row.key, row.value, row.custom]
                        .join(' ')
                        .toLowerCase()
                        .indexOf(query.toLowerCase()) >= 0;
                };
            }

            currentPage = 0;
            $currentPage.setValue(1);
            maxPage = Math.ceil(data.filter(currentFilter).length / entriesPerPage);
            $customTranslationTablePager.down('.page-number').update(maxPage);
            renderTable(currentPage);
        });

        $filterAbort.on('click', function () {
            $filterInput.setValue('');

            $filterProcess.simulate('click');
        });

        $customTranslationTable.down('tbody').on('change', 'input', function (ev) {
            const $input = ev.findElement('input');
            const key = $input.readAttribute('data-key');

            customDatum = data.find(function(datum) { return datum.key === key; });

            customDatum.custom = $input.getValue();
            customDatum.changed = true;
        });

        // Prevent 'accidental' submit of the page, when hitting enter.
        $customTranslationForm.on('keydown', 'input', function (ev) {
            if (ev.key === 'Enter') {
                ev.preventDefault();
            }
        });

        $currentPage.on('change', function () {
            currentPage = Math.min(maxPage - 1, Math.max($currentPage.getValue() - 1, 0));

            if (isNaN(currentPage)) {
                currentPage = 0;
            }

            $currentPage.setValue(currentPage + 1);
            renderTable(currentPage);
        });

        $('custom-translation-table-pager-prev').on('click', function () {
            currentPage = Math.max(currentPage - 1, 0);

            $currentPage.setValue(currentPage + 1);
            renderTable(currentPage);
        });

        $('custom-translation-table-pager-next').on('click', function () {
            currentPage = Math.min(maxPage - 1, currentPage + 1);

            $currentPage.setValue(currentPage + 1);
            renderTable(currentPage);
        });

        function renderTable(page) {
            $customTranslationFormOverlay.removeClassName('hide');

            const $tableBody = $customTranslationTable.down('tbody').update();
            const dataCopy = data.filter(currentFilter).slice(page * entriesPerPage, page * entriesPerPage + entriesPerPage);
            let index;

            for (index = 0; index < dataCopy.length; index ++) {
                const languageConstant = new Element('td');
                languageConstant.innerText = dataCopy[index].key;

                const languageTranslation = new Element('td');
                languageTranslation.innerText = dataCopy[index].value;

                $tableBody
                    .insert(new Element('tr')
                        .update(languageConstant)
                        .insert(languageTranslation)
                        .insert(new Element('td')
                            .update(new Element('input', {
                                type:            'text',
                                className:       'input input-block',
                                'data-key':      dataCopy[index].key,
                                'data-previous': dataCopy[index].custom,
                                value:           dataCopy[index].custom,
                                autocomplete:    'off'
                            }))));
            }

            idoit.callbackManager.registerCallback('smarty-ajax-file-upload', function (result) {
                $('C__CUSTOM_TRANSLATION__FLAG_UPLOAD')
                    .up('td')
                    .insert(new Element('p', { className: 'mt10 p5 box box-green' }).update('[{isys type="lang" ident="LC__LANGUAGE_FLAG_UPLOAD_COMPLETE"}]'))
            });

            [{if !$allowedToEdit}]
            $tableBody.select('input').invoke('disable');
            [{/if}]

            $customTranslationFormOverlay.addClassName('hide');
        }
    })();
</script>
