<script>
    (function() {

        function init() {
            $('[note-rte]').each(function() {

                $(this).wrap(
                    $('<div class="border-left border-right rte-holder"/>')
                        .attr('data-shortcuts', '')
                );

                // give a unique id to this editor instance
                var editorID = Math.ceil(Math.random() * 99999),
                    fieldName = this.name;

                var el = this;
                var existingContent = $(el).attr('data-content');
                var quill = new Quill(el, {
                    theme: 'snow',
                    modules: stagQuillConfig
                });

                var toolbar = $(quill.container).prev('.ql-toolbar');

                // add button for new shortcut
                var newSCButton = $('<button class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
                    'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
                toolbar.append(newSCButton);

                quill.root.innerHTML = existingContent;

                quill.on('text-change', function(delta, oldDelta, source) {
                    var content = quill.root.innerHTML;
                    var dataValue = JSON.stringify({
                        value: content
                    });
                    var dataField = $(el).closest('.note-section').find('input[name=data]').val(dataValue);
                });

                $(quill.container)
                    .find('.ql-editor[contenteditable]')
                    .attr('data-field', fieldName)
                    .attr('data-editor-id', editorID)
                    .attr('with-shortcuts', 1);
            })

            $('[btn-save-form]').on('click', function() {
                doSave($(this).closest('.note-section'));
            });

            @if(isset($guestAccessCode))
                $('.note-section form').append("<input type='hidden' name='guest_access_code' value='{{$guestAccessCode}}'/>");
            @endif

            // copy link
            $(document)
                .off('click.copy', '.copy-link')
                .on('click.copy', '.copy-link', function() {
                    var copyText = $('#' + $(this).attr('data-id'));
                    copyText.focus().select();
                    document.execCommand("copy");
                    toastr.success("The link " + copyText.val() + " has been copied to the clipboard");
                    return false;
                });

            // [name="data"] change listener
            $('.note-section input[name="data"], .note-section input[name="items"]').each(function() {
                initChangeListener($(this));
            });
        }

        const debounce = (func, wait) => {
            let timeout;

            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };

                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        };

        function doSave(_section) {
            console.log(_section.attr('data-section-template-name'));

            _section.find('[btn-save-form]').prop('disabled', true);
            _section.find('.text-saving').removeClass('d-none');
            _section.find('.text-saved').addClass('d-none');

            var dataField = _section.find('input[name=data]')
            var value = $(dataField).val();

            var summaryContainer = _section.find('.summary-container')

            var sectionUid = _section.attr('data-section-uid')

            var _form = _section.find('form[processed]')[0];
            if(_form){
                console.log("Form found. submitting normally");
                $.post("/process_form_submit", $(_form).serialize(), function(resp) {
                    handleSubmitResponse(resp,_section, summaryContainer)
                }, 'json');
            }else{
                console.log("Form not found.");
                var dataToPost = {
                    "section_uid": sectionUid,
                    "data": value,
                }
                @if(isset($guestAccessCode))
                    dataToPost['guest_access_code'] = '{{$guestAccessCode}}';
                @endif
                $.post("/process_form_submit", dataToPost, function(resp) {
                    handleSubmitResponse(resp,_section, summaryContainer)
                }, 'json');
            }
        }

        function handleSubmitResponse(resp,_section, summaryContainer){
            $('body').removeClass('blocking-mode');
            hideMoeFormMask();
            if (resp.success) {
                summaryContainer.html(resp.newSummaryHtml);
            }
            _section.find('[btn-save-form]').prop('disabled', false);
            _section.find('.text-saving').addClass('d-none');
            if(resp.success) {
                _section.find('.text-saved').text('Last saved at ' + (new Date().toLocaleTimeString())).removeClass('d-none');
            }
        }

        function initChangeListener(_elem) {
            new MutationObserver(debounce(function() {
                if(_elem.closest('.note-section').is('.edit')) {
                    // console.log('ALIX: In edit mode. Auto-saving', _elem.closest('.note-section').attr('data-section-template-name'))
                    $('body').addClass('blocking-mode');
                    showMoeFormMask('blocking-overlay');
                    doSave(_elem.closest('.note-section'));
                }
                else {
                    // console.log('ALIX: Not in edit mode. Not auto-saving', _elem.closest('.note-section').attr('data-section-template-name'))
                }
            }, 250))
            .observe(_elem[0], {
                attributes: true
            });
        }

        addMCInitializer('note-sections-list', init);

    })();
</script>
