{#
 # ---------------------------------------------------------------------
 #
 # GLPI - Gestionnaire Libre de Parc Informatique
 #
 # http://glpi-project.org
 #
 # @copyright 2015-2025 Teclib' and contributors.
 # @licence   https://www.gnu.org/licenses/gpl-3.0.html
 #
 # ---------------------------------------------------------------------
 #
 # LICENSE
 #
 # This file is part of GLPI.
 #
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
 #
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
 #
 # ---------------------------------------------------------------------
 #}

{% import 'components/form/fields_macros.html.twig' as fields %}
{% import 'components/form/basic_inputs_macros.html.twig' as inputs %}
{% set rand = random() %}

<div class="card-body d-flex flex-wrap">
    <div class="col-12 col-xxl-12 flex-column">
        <div class="d-flex flex-row flex-wrap flex-xl-nowrap">
            <div class="row flex-row align-items-start flex-grow-1">
                <div class="row flex-row">
                    <form id="domain_record_data{{ rand }}" data-submit-once>
                        {% for field in fields %}
                            {% set input_attrs = {
                                'placeholder': field['placeholder']|default(''),
                                'data-quote-value': (field['quote_value'] ?? false) ? 'true' : 'false',
                                'data-is-fqdn': (field['is_fqdn'] ?? false) ? 'true' : 'false',
                            } %}
                            {% if not (field['quote_value'] ?? false) %}
                                {# prevent usage of spaces in unquoted values #}
                                {% set input_attrs = input_attrs|merge({
                                    'pattern': '[^\\s]+'
                                }) %}
                            {% endif %}
                            {{ fields.textField(field['key'], '', field['label'], {
                                additional_attributes: input_attrs,
                                rand: rand,
                                full_width: true,
                            }) }}
                        {% endfor %}
                        <div class="d-flex flex-row-reverse">
                            {{ inputs.submit('save', _x('button', 'Save'), 1) }}
                        </div>
                        <script>
                            $(() => {
                                const form = $('#domain_record_data{{ rand }}');

                                // Put existing data into fields
                                let data_to_copy = $('#{{ str_input_id }}').val();
                                form.find('input').each(function () {
                                    let endoffset = 0;
                                    if ($(this).data('quote-value')) {
                                        // Search for closing quote (quote inside value are escaped by a \)
                                        do {
                                            endoffset = endoffset + 1; // move to next char (ignore opening or escaped quote)
                                            endoffset = data_to_copy.indexOf('" ', endoffset);
                                        } while (endoffset !== -1 && data_to_copy.charAt(endoffset - 1) === '\\');

                                        if (endoffset !== -1) {
                                            endoffset += 1; // capture closing quote
                                        }
                                    } else {
                                        endoffset = data_to_copy.indexOf(' ');
                                    }

                                    if (endoffset === -1) {
                                        endoffset = data_to_copy.length; // get whole value if no separator found
                                    }

                                    let value = data_to_copy.substring(0, endoffset).trim();
                                    if ($(this).data('quote-value')) {
                                        value = value.replace(/^"/, '').replace(/"$/, ''); // trim surrounding quotes
                                        value = value.replace('\\"', '"'); // unescape quotes
                                    }
                                    $(this).val(value);

                                    // "endoffset + 1" to strip also ' ' separator char
                                    data_to_copy = data_to_copy.substring(endoffset + 1);
                                });

                                // Copy values into data input on submit
                                form.on('submit', function (event) {
                                    event.preventDefault();

                                    const data_tokens = [];
                                    const data_obj = {};
                                    $(this).find('input').each(function () {
                                        let value = $(this).val();
                                        data_obj[$(this).attr('name')] = value; // keep raw value

                                        if ($(this).data('is-fqdn') && !value.match(/\.$/)) {
                                            value += '.'; // add ending dot
                                        }
                                        if ($(this).data('quote-value') && !value.match('/^".*"$/')) {
                                            value = '"' + value.replace('"', '\\"') + '"';
                                        }
                                        data_tokens.push(value);
                                    });

                                    $('#{{ str_input_id }}').val(data_tokens.join(' '));
                                    $('#{{ obj_input_id }}').val(JSON.stringify(data_obj));
                                });
                            });
                        </script>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
