const cneTemplatePickerFields = ['protocol', 'service'];// Define fields that need to use Picker
window.addItem = function(containerId, itemClass, fieldsConfig)
{
    const container = $(`#${containerId}`);
    const counter   = container.find(`.${itemClass}`).length;
    const newLine   = container.find(`.${itemClass}`).first().clone(true);
    fieldsConfig.forEach(field =>
    {
        if (cneTemplatePickerFields.includes(field))
        {
            const pickerInstance = zui.Picker.query(`[name="settings[${itemClass}][0][${field}]"]`);
            const options        = pickerInstance.options;
            const pickerBox      = newLine.find('.form-group-wrapper.picker-box');
            pickerBox.attr('id', `${itemClass}${field}${counter}`);

            options.name         = `settings[${itemClass}][${counter}][${field}]`;
            options.defaultValue = '';
            options.disabled     = false;
            options.placeholder  = '';
            new zui.Picker(pickerBox, options);
        }
        else
        {
            newLine.find(`input[name="settings[${itemClass}][0][${field}]"]`)
                .attr('name', `settings[${itemClass}][${counter}][${field}]`)
                .attr('id', `settings[${itemClass}][${counter}][${field}]`)
                .val('');
        }
    });
    newLine.find('.sub-input').addClass('mt-2');
    newLine.find('.sub-label').addClass('hidden');
    container.append(newLine);
    container.find(`.del-${itemClass}`).removeClass('invisible');
};

window.delItem = function(containerId, itemClass, element)
{
    const container = $(`#${containerId}`);
    const items     = container.find(`.${itemClass}`);
    if (items.length > 1)
    {
        $(element.target).closest(`.${itemClass}`).remove();
        const remainingItems = container.find(`.${itemClass}`);
        remainingItems.each((index, item) =>
        {
            const $item = $(item);
            cneTemplatePickerFields.forEach(field =>
            {
                const pickerBox = $item.find(`.picker-box[id*="${itemClass}${field}"]`);
                if (pickerBox.length)
                {
                    pickerBox.attr('id', `${itemClass}${field}${index}`);
                    const picker = zui.Picker.query(pickerBox);
                    if (picker) picker.options.name = `settings[${itemClass}][${index}][${field}]`;
                }
            });

            $item.find('input').each(function()
            {
                const name = $(this).attr('name');
                if (name) $(this).attr('name', name.replace(/\[\d+\]/, `[${index}]`));
            });
        });

        if (remainingItems.length === 1) remainingItems.find(`.del-${itemClass}`).addClass('invisible');
    }
};

window.addPorts = () => addItem('ports', 'ports', ['protocol', 'port', 'desc']);
window.delPorts = (element) => delItem('ports', 'ports', element);

window.addDirs = () => addItem('dirs', 'dirs', ['dir', 'desc']);
window.delDirs = (element) => delItem('dirs', 'dirs', element);

window.addEnvs = () => addItem('envs', 'envs', ['key', 'value']);
window.delEnvs = (element) => delItem('envs', 'envs', element);

window.addServices = () => addItem('services', 'services', ['service', 'desc']);
window.delServices = (element) => delItem('services', 'services', element);

window.getClusterByEnv = function (clusterID = 0)
{
    toggleLoading('#publishtemplateCreateForm', true);
    const $picker = $('[name=clusterID]').zui('picker');
    $picker.$.clear();
    const envID = $('[name=envID]').val();
    $.getJSON($.createLink('cluster', 'ajaxGetCluster', 'envID=' + envID), function (items)
    {
        $picker.render({items: items});
        if (typeof items !== 'undefined')
        {
            const matchedItem = items.find(item => item.value === clusterID);
            if (matchedItem) $picker.$.setValue(matchedItem.value);
        }
        toggleLoading('#publishtemplateCreateForm', false);
    });
};
