<script>
    (function() {

        window.updateAllSegmentsInResponse = function(_response, _updateListeners = true, _updateOnlySummary = false) {
            if(!hasResponseError(_response)) {

                // refresh primary segment (where uid is _response.data.uid)
                if(_response.data && _response.data.uid) {
                    updateSegmentByUid(_response.data.uid, _response.data.summaryHtml, _response.data.editHtml, _updateOnlySummary);
                }

                // refresh rhs-sidebar
                window.refreshRHSSidebar();

                // refresh listening segments
                if(_updateListeners) {
                    if(_response.data && _response.data.listenerSegmentUids && _response.data.listenerSegmentUids.length) {
                        for (let i=0; i<_response.data.listenerSegmentUids.length; i++) {
                            let listenerSegment = $('.note-section[data-segment-uid="' + _response.data.listenerSegmentUids[i] + '"]');
                            let listenerSegmentTemplateName = listenerSegment.attr('data-segment-template-name');
                            if(listenerSegment && listenerSegment.length) {
                                $.post('/api/visit/updateSegmentHtml', {
                                    segmentUid: _response.data.listenerSegmentUids[i]
                                }, _data => {
                                    updateAllSegmentsInResponse(_data, false, _updateOnlySummary);

                                    // ugly hack!
                                    if(listenerSegmentTemplateName === 'medrisk_vigilence') {
                                        $('.mrv-trigger')
                                            .empty()
                                            .append('<div class="text-info font-weight-bold text-center font-size-11">MRV</div>')
                                            .append(_data.data.summaryHtml);
                                    }

                                }, 'json');
                            }
                        }
                    }
                }
            }
        }

        window.refreshRHSSidebar = function() {
            let noteRHSSidebar = $('#note-rhs-sidebar');
            if(noteRHSSidebar.length) {
                let lastUpdatedAt = noteRHSSidebar.attr('last-updated-at');
                if(lastUpdatedAt) {
                    lastUpdatedAt = +lastUpdatedAt;
                    if(new Date().getTime() - lastUpdatedAt < 500) { // dont refresh if refreshed less than a second ago
                        console.log('Skipping rhs sidebar refresh');
                        return false;
                    }
                }
                noteRHSSidebar.attr('last-updated-at', new Date().getTime());
                $.get('/note-rhs-sidebar/{{$patient->uid}}/{{$note->uid}}', _data => {
                    noteRHSSidebar
                        .empty()
                        .html($(_data).html());
                    $(window).trigger('scroll');
                });
            }
        };

        window.updateSegmentByUid = function(_uid, _summaryHtml, _editHtml, _updateOnlySummary) {
            let segment = $('.note-section[data-segment-uid="' + _uid + '"]');
            if(segment && segment.length) {
                segment.find('.summary-container').html(_summaryHtml);
                if(!_updateOnlySummary) segment.find('.edit-container').html(_editHtml);

                // special case for lifestyle
                let popupContainer = $('[stag-popup-key="segment-popup-' + segment.attr('data-segment-template-name') + '"] .ls-segment-edit-html');
                if(popupContainer.length) {
                    popupContainer.html(_editHtml);
                }

                // refresh rhs-sidebar
                window.refreshRHSSidebar();

                if(!_updateOnlySummary) {
                    initRTEs(segment);
                    initSegmentMoes(segment);
                    initMoes();
                    initStagSuggest();
                    if(window.segmentInitializers) {
                        let internalName = segment.attr('data-segment-template-name');
                        if(window.segmentInitializers.hasOwnProperty(internalName) &&
                            typeof window.segmentInitializers[internalName] === 'function') {
                            window.segmentInitializers[internalName].call(window);
                        }
                    }
                }
            }
        }

        window.updateSegmentFromObject = function(_object) {
            let segment = $('.note-section[data-segment-uid="' + _object.segmentUid + '"]');
            if(segment && segment.length) {
                segment.find('.summary-container').html(_object.summaryHtml);
                segment.find('.edit-container').html(_object.editHtml);
                initRTEs(segment);
                initSegmentMoes(segment);
                initMoes();
                initStagSuggest();
                if(window.segmentInitializers) {
                    let internalName = segment.attr('data-segment-template-name');
                    if(window.segmentInitializers.hasOwnProperty(internalName) &&
                        typeof window.segmentInitializers[internalName] === 'function') {
                        window.segmentInitializers[internalName].call(window);
                    }
                }
            }
        }

        window.autoSaveSegment = function(_trigger) {
            saveVisitForm(_trigger, true);
        };

        window.autoSaveSegmentAndClose = function(_trigger) {
            saveVisitForm(_trigger, true, true);
        };

        window.initRequestToAddAProblem = function(){
            //On any input/select etc, add these attribute:
            // data-problem="Sneezing"
            // data-problem-value="Yes" Note: this is the value to compare with to trigger problems center popup

            var problemInput = $('[data-problem]');
            problemInput.on('change', function(e){
                var input = e.target;
                var value = input.value;
                var isProblemIfAnswerIs = $(input).data('problem-value');
                if(value === isProblemIfAnswerIs){
                    if (confirm("Do you want to add this as a problem?") == true) {
                        $('#active-problems').click();
                    } else {
                       //Do nothing for now
                    }
                    
                }
            });
        };

        function initRTEs(_parent) {
            _parent.find('[note-rte]:not(.ql-container)').each(function() {

                let noteRTE = $(this);

                $(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).attr('data-field-name') ? $(this).attr('data-field-name') : 'free_text';

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

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

                // add button for new shortcut
                if(!noteRTE.is('[use-shortcuts]') || !noteRTE.attr('use-shortcuts')) {
                    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;

                let setValue = function(delta, oldDelta, source) {
                    var content = quill.root.innerHTML;
                    let dataObject = {};
                    dataObject[fieldName] = content;
                    var dataValue = JSON.stringify(dataObject);
                    let pElem = $(el).closest('[visit-moe]');
                    if(!pElem.length) {
                        pElem = $(el).closest('form');
                    }
                    let v = pElem.find('input[name=data]').val();
                    if(!!v) {
                        try {
                            v = JSON.parse(v);
                            v[fieldName] = content;
                            v = JSON.stringify(v);
                        }
                        catch (e) {
                            v = JSON.stringify(dataObject);
                        }
                    }
                    else {
                        v = JSON.stringify(dataObject);
                    }
                    pElem.find('input[name=data]').val(v);
                }

                let onTextChange = function(delta, oldDelta, source) {
                    setValue(delta, oldDelta, source);
                    $(el).trigger('rich-text-input');
                }

                quill.on('text-change', onTextChange);

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

                // set value initially
                setValue();
            });
        }

        function init() {
            initRequestToAddAProblem();

            $(document)
                .off('input.auto-grow', '[visit-moe] form textarea')
                .on('input.auto-grow', '[visit-moe] form textarea', function() {
                    this.style.minHeight = "calc(1.5em + .5rem + 2px)";
                    this.style.height = "calc(1.5em + .5rem + 2px)";
                    this.style.height = (this.scrollHeight)+"px";
                });

            let parent = $('.segments-list');
            initRTEs(parent);
            initSegmentMoes(parent);
            initStagSuggest();

            // check and run all segment initializers
            try {
                if(window.segmentInitializers) {
                    for(let x in window.segmentInitializers) {
                        if(window.segmentInitializers.hasOwnProperty(x) && typeof window.segmentInitializers[x] === 'function') {
                            window.segmentInitializers[x].call(window);
                        }
                    }
                }
            }
            catch (e) {
                console.warn('Error running 1 or more segment initializers.')
            }

            // refresh segment
            $(document)
                .off('click.refresh-segment', '.refresh-segment')
                .on('click.refresh-segment', '.refresh-segment', function() {
                    // showMask();
                    let noteSection = $(this).closest('.note-section');
                    noteSection.addClass('refreshing');
                    $.post('/api/visit/updateSegmentHtml', {
                        segmentUid: $(this).attr('data-segment-uid')
                    }, _data => {
                        // hideMask();
                        noteSection.removeClass('refreshing');
                        updateAllSegmentsInResponse(_data);
                    }, 'json');
                    return false;
                });

            // ls segment special vase
            $(document)
                .off('click.ls-segment-trigger', '.ls-segment-trigger[data-target]')
                .on('click.ls-segment-trigger', '.ls-segment-trigger[data-target]', function() {
                    $('.note-section.edit-trigger[data-segment-template-name="' + $(this).attr('data-target') + '"]').trigger('click');
                    return false;
                });

            // link to other segments by internal_name
            $(document)
                .off('click.segment-trigger', '.segment-trigger[data-target]')
                .on('click.segment-trigger', '.segment-trigger[data-target]', function() {
                    $('.note-tree-node [data-segment-internal-name="' + $(this).attr('data-target') + '"]').trigger('click');
                    return false;
                });

            /*
            $('[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));
            });
             */

            // relevance
            $(document).off('change', '.visit-segment[data-segment-template-name] .chk-relevance');
            $(document).on('change', '.visit-segment[data-segment-template-name] .chk-relevance', function () {
                let segment = $(this).closest('.visit-segment');
                if(this.checked) {
                    $.post('/api/visitPoint/markPointRelevantToNote', {
                        noteUid: '{{$note->uid}}',
                        pointUid: $(this).attr('data-point-uid')
                    }, _data => {
                        if(!hasResponseError(_data)) {
                            segment.find('.refresh-segment').trigger('click');
                        }
                    }, 'json');
                }
                else {
                    if($(this).attr('data-rel-uid')) {
                        $.post('/api/visitPoint/undoMarkPointRelevantToNote', {
                            uid: $(this).attr('data-rel-uid')
                        }, _data => {
                            if(!hasResponseError(_data)) {
                                segment.find('.refresh-segment').trigger('click');
                            }
                        }, 'json');
                    }
                    else {
                        console.log('Error - missing rel uid');
                    }
                }
                return false;
            });

            const debounce = (func, wait) => {
                let timeout;
                return function executedFunction(...args) {
                    const later = () => {
                        clearTimeout(timeout);
                        func(...args);
                    };
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                };
            };

            let debouncedSaver = debounce(function(_trigger) {
                let parent = $(_trigger).closest('.visit-segment');
                if(!parent.length) parent = $(_trigger).closest('form');
                parent.find('.autosave-indicator').removeClass('show');
                parent.find('.autosave-indicator.saving').addClass('show');
                saveVisitForm(_trigger, true, false, () => {
                    parent.find('.autosave-indicator').removeClass('show');
                    parent.find('.autosave-indicator.saved').addClass('show');
                });
            }, 500);

            // auto save for segments with edit-mode
            $(document).off('input.auto-save-input', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form input[type="text"]');
            $(document).on('input.auto-save-input', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form input[type="text"]', function () {
                debouncedSaver(this);
            });
            $(document).off('change.auto-save-select-change', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form select');
            $(document).on('change.auto-save-select-change', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form select', function () {
                debouncedSaver(this);
            });
            $(document).off('change.auto-save-checkbox-change', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form input[type="checkbox"]');
            $(document).on('change.auto-save-checkbox-change', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form input[type="checkbox"]', function () {
                debouncedSaver(this);
            });
            $(document).off('change.auto-save-radio-change', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form input[type="radio"]');
            $(document).on('change.auto-save-radio-change', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form input[type="radio"]', function () {
                debouncedSaver(this);
            });
            $(document).off('input.auto-save-textarea-input', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form textarea');
            $(document).on('input.auto-save-textarea-input', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form textarea', function () {
                debouncedSaver(this);
            });

            $(document).off('rich-text-input.auto-save-rich-text-input', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form [note-rte]');
            $(document).on('rich-text-input.auto-save-rich-text-input', '.visit-segment.edit[data-segment-template-name] [visit-moe]:not([no-auto-save]) form [note-rte]', function () {
                debouncedSaver(this);
            });

            $(document).off('save-trigger.auto-save-input', '[visit-moe] form input[type="hidden"]');
            $(document).on('save-trigger.auto-save-input', '[visit-moe] form input[type="hidden"]', function () {
                debouncedSaver(this);
            });
        }

        addMCInitializer('note-segments-list', init, '#note-segments-list');

    })();
</script>
