[{isys_group name="tom.popup.custom-fields"}]
<div id="custom-fields-attribute-configuration-popup">
    <div class="popup-header-ng">
        <h1>[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__PROPERTY"}] "[{$propertyTitle|escape:"html"}]"</h1>
        <button type="button" class="btn btn-secondary popup-closer ml-auto" title="[{isys type="lang" ident="LC__POPUP__CLOSE"}]" data-tooltip="1">
            <img alt="close" src="[{$dir_images}]axialis/user-interface/window-control-close.svg" />
        </button>
    </div>

    <div class="popup-content">
        <table class="contentTable">
            <tr>
                <td class="key vat">[{isys type="f_label" name="field_type" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_TYPE"}]</td>
                <td class="value">[{isys name="field_type" type="f_dialog"}]</td>
            </tr>
            <tr class="notice hide">
                <td></td>
                <td>
                    <div class="box-blue p5 mr20 ml20">
                        <img src="[{$dir_images}]axialis/basic/button-info.svg" class="vam mr5">
                        <span class="van"><!-- Will be filled by JS --></span>
                    </div>
                </td>
            </tr>
            <tr>
                <td class="key vat">[{isys type="f_label" name="field_title" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_TITLE"}]</td>
                <td class="value">
                    <div data-type="single-line">
                        [{isys name="field_title" type="f_text" p_bNoTranslation="1"}]
                    </div>
                    <div data-type="multi-line" class="ml20 mr20">
                        [{isys name="field_title_multiline" type="f_textarea"}]
                        <div id="field_title_multiline_ace"><!-- Will be filled by JS --></div>
                    </div>
                </td>
            </tr>
            <tr>
                <td class="key vat">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_ADDITIONAL"}]</td>
                <td class="value">
                    [{isys name="field_identifier" type="f_text"}]
                    [{isys name="field_dialog_default" type="f_dialog"}]
                    [{isys name="field_relation" type="f_dialog"}]
                    [{isys name="field_report" type="f_dialog"}]
                </td>
            </tr>
            <tr class="dependency-field hide">
                <td class="key vat">
                    <img src="[{$dir_images}]axialis/basic/button-info.svg" class="mr5 vam mouse-help" title="[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__DEPENDENCY_INFO"|escape:"html"}]" />
                    [{isys type="f_label" name="field_dialog_dependency" ident="LC__SYSTEM__CUSTOM_CATEGORIES__DEPENDENCY"}]
                </td>
                <td class="value">[{isys name="field_dialog_dependency" type="f_dialog"}]</td>
            </tr>
            <tr class="dependency-field hide">
                <td class="key vat">[{isys type="f_label" name="field_dialog_linked_to" ident="LC__SYSTEM__CUSTOM_CATEGORIES__LINKED_TO"}]</td>
                <td class="value">[{isys name="field_dialog_linked_to" type="f_dialog"}]</td>
            </tr>
            <tr>
                <td class="key vat">[{isys type="f_label" name="field_visibility" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_HANDLING"}]</td>
                <td class="value">[{isys name="field_visibility" type="f_dialog"}]</td>
            </tr>
            [{if $isMultivalueCategory}]
            <tr>
                <td class="key vat">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__SHOW_IN_LIST"}]</td>
                <td class="value"><input type="checkbox" name="field_show_in_list" value="1" [{if $showInLine}]checked="checked"[{/if}] /></td>
            </tr>
            [{/if}]
            <tr>
                <td colspan="2">
                    <hr class="mt5 mb5" />
                </td>
            </tr>
            <tr class="change-key-button [{if $changedKey}]hide[{/if}]">
                <td></td>
                <td class="value pl20">
                    <button type="button" class="btn"><span>[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__CHANGE_KEY"}]</span></button>
                </td>
            </tr>
            <tr class="change-key-row [{if !$changedKey}]hide[{/if}]">
                <td class="key vat">[{isys type="f_label" name="field_key" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY"}]</td>
                <td class="value">
                    [{isys name="field_key" type="f_text"}]
                    <div class="cb pl20 pt10 text-blue">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__DESCRIPTION" p_bHtmlEncode=false}]</div>
                </td>
            </tr>
        </table>
    </div>

    <div class="popup-footer-ng">
        <button type="button" class="btn mr5 save-configuration">
            <img src="[{$dir_images}]axialis/basic/symbol-ok.svg" /><span>[{isys type="lang" ident="LC_UNIVERSAL__ACCEPT"}]</span>
        </button>

        <button type="button" class="btn popup-closer">
            <img src="[{$dir_images}]axialis/basic/symbol-cancel.svg" /><span>[{isys type="lang" ident="LC_UNIVERSAL__ABORT"}]</span>
        </button>

        <button type="button" class="btn ml-auto delete-configuration">
            <img src="[{$dir_images}]axialis/basic/button-remove.svg" /><span>[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_REMOVE"}]</span>
        </button>
    </div>
</div>

<script type="text/javascript">
    (function () {
        'use strict';

        const $popup = $('custom-fields-attribute-configuration-popup');
        const $fieldType = $popup.down('[name="field_type"]');
        const $changeKeyButton = $popup.down('.change-key-button');
        const $changeKeyRow = $popup.down('.change-key-row');
        const $keyInput = $('field_key');
        const otherProps = JSON.parse('[{$otherProps|json_encode|escape:"javascript"}]');
        let keyIsValid = true;

        const cleanKey = (key) => key
            .toLowerCase()
            .replaceAll(/[\s-]+/g, '_')
            .replaceAll(/_+/g, '_')
            .replaceAll(/[^a-z0-9_]/g, '')
            .trim();

        $keyInput.on('keydown', (ev) => {
            const key = ev.key.toLowerCase();

            if (key === 'Enter' || key.match(/[^a-z0-9_\s-]/) !== null) {
                ev.preventDefault();
                return false;
            }
        });

        $keyInput.on('keyup', (ev) => {
            $keyInput.setValue(cleanKey($keyInput.getValue()));
        });

        $keyInput.on('change', (ev) => {
            keyIsValid = false;
            const value = cleanKey($keyInput.getValue())
                .replaceAll(/(^_|_$)/g, '')
                .trim();

            if (value === '') {
                $keyInput.setValue('[{$key}]');
                idoit.Notify.error('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__NOT_EMPTY"}]');
                return;
            }

            if (value.length > 64) {
                $keyInput.setValue('[{$key}]');
                idoit.Notify.error('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__TOO_LONG"}]');
                return;
            }

            // Keys are not allowed to be 'numeric'
            if (/^\d+$/.test(value)) {
                $keyInput.setValue('[{$key}]');
                idoit.Notify.error('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__NOT_NUMERIC"}]');
                return;
            }

            // Check if the property key is used for a different property.
            const found = otherProps.filter((prop) => prop.key === value || prop.newKey === value);

            if (found.length) {
                $keyInput.setValue('[{$key}]');
                idoit.Notify.error('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__KEY_USED"}]');
                return;
            }

            new Ajax.Request(idoit.Router.getRoute('custom_fields.ajax.find-property-by-key'), {
                method: 'GET',
                parameters: {
                    id:  '[{$id}]',
                    key: value
                },
                onComplete: function (xhr) {
                    if (!is_json_response(xhr, true)) {
                        return;
                    }

                    if (xhr.responseJSON.data !== null) {
                        $keyInput.setValue('[{$key}]');
                        idoit.Notify.error('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__KEY_USED_SOMEWHERE_ELSE"}]');
                        return;
                    }

                    $keyInput.setValue(value);
                    keyIsValid = true;
                    idoit.Notify.success('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__CHECKED"}]', { life: 3 });
                }
            });
        });

        $changeKeyButton.on('click', 'button', () => {
            $changeKeyButton.addClassName('hide');
            $changeKeyRow.removeClassName('hide');
        });

        idoit.Require
            .addModule('custom-fields.attribute-configuration-popup', '[{isys_module_custom_fields::getWwwPath()}]assets/js/attribute-configuration-popup.js')
            .requireQueue(['custom-fields.attribute-configuration-popup', 'ace', 'aceLanguageTools'], function () {
                window.ace.require('ace/ext/language_tools');

                const editor = window.ace.edit('field_title_multiline_ace', {
                    theme: 'ace/theme/clouds',
                    mode: 'ace/mode/javascript',
                    minLines: 10,
                    maxLines: 30,
                    enableBasicAutocompletion: true,
                    enableSnippets: false,
                    enableLiveAutocompletion: true
                });

                const editorSession = editor.getSession();
                const $multilineTitle = $('field_title_multiline');

                editorSession.setValue($multilineTitle.getValue());

                // @see ID-9578 Validate user input in case of 'code' (HTML / Javascript).
                editorSession.on('changeAnnotation', function (e) {
                    const annotations = editorSession.getAnnotations();
                    const $saveButton = $popup.down('.save-configuration');

                    $saveButton.writeAttribute('title', null);
                    $saveButton.enable();

                    // @see ID-9621 Don't run any further logic, if the type is not HTML or Javascript.
                    if (!['html', 'script'].include($fieldType.getValue())) {
                        return;
                    }

                    if (Array.isArray(annotations) && annotations.filter((annotation) => annotation.type === 'error').length) {
                        $saveButton.writeAttribute('title', '[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__INPUT_CODE_INVALID"}]');
                        $saveButton.disable();
                    }
                });

                editorSession.on('change', function (e) {
                    $multilineTitle.setValue(editorSession.getValue());
                });

                const configPopup = new window.AttributeConfigurationPopup($popup, {
                    dialogYesNoDefaults: JSON.parse('[{$dialogYesNoDefaults|json_encode|escape:"javascript"}]'),
                    calendarDefaults: JSON.parse('[{$calendarDefaults|json_encode|escape:"javascript"}]'),
                    singleLineFields: JSON.parse('[{$singleLineFields|json_encode|escape:"javascript"}]'),
                    badIdentifierWords: JSON.parse('[{$badIdentifierWords|json_encode|escape:"javascript"}]'),
                    aceInstance: editor
                });

                $popup.on('click', '.popup-closer', function () {
                    popup_close();
                });

                $popup.on('click', '.save-configuration', function () {
                    if (keyIsValid) {
                        const configuration = configPopup.getConfiguration();
                        configuration.key = '[{$key}]';
                        configuration.newKey = $keyInput.getValue();

                        $('area').fire('field:update', configuration);
                        popup_close();
                    } else {
                        idoit.Notify.info('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_KEY__CHECKING"}]', { life: 3 });
                    }
                });

                $popup.on('click', '.delete-configuration', function () {
                    $('area').fire('field:remove', { key: '[{$key}]' });
                    popup_close();
                });
            });
    })();
</script>

<style>
    .ace_editor {
        border: 1px solid #787979;
    }

    #custom-fields-attribute-configuration-popup table tr {
        height: 30px;
    }

    #custom-fields-attribute-configuration-popup table td:first-child {
        width: 120px;
        text-align: right;
    }

    #custom-fields-attribute-configuration-popup input[type="checkbox"] {
        margin-left: 20px;
    }
</style>
[{/isys_group}]
