import SortApi from './modules/SortApi';

define(['jquery'], function ($) {
    return function () {
        const sortApi = new SortApi();
        const settingsTabSelector = '#settings_tab'
        let settingsForm = '';

        $('ul#sectionList').sortable({
            handle: '.section-drag-handler',
            connectWith: 'ul#sectionList',
            beforeStop: function(e, ui) {
                sortApi.update($(this).sortable('toArray'), false)
            }
        });

        // question list
        $('ul#questionList').sortable({
            handle: '.question-drag-handler',
            connectWith: 'ul#questionList',
            beforeStop: function (e, ui) {
                sortApi.update($(this).sortable('toArray'), true)
            },
            /** Moved item to other section */
            receive: function(e, ui) {
                let section_id = $(this).parent().attr('id')
                let array_with_questions_id = $(this).sortable('toArray')

                sortApi.modifyUrls(ui.item, section_id)

                const promise = new Promise((resolve, reject) => resolve(array_with_questions_id))

                promise.then(resolve => {
                    sortApi.move(section_id, array_with_questions_id)
                }).then(resolve => {
                    sortApi.update($(this).sortable('toArray'), true)
                })
            }
        });

        // update 'settingsForm' variable with form data when user open tab settings
        $(settingsTabSelector).on('click', function () {
            settingsForm = $("#create_survey").serializeArray();
        });

        // on any changes in tab settings
        $(settingsTabSelector).on('change', function () {
            // when user will change anything in setting tab - add onbeforeunload alert
            if ($("#create_survey").serializeArray() !== settingsForm) {

                // add onbeforeunload alert
                window.onbeforeunload = function() {
                    return '';
                };
            }

            // remove onbeforeunload alert on submit/draft/archive
            $('#create_survey button').on('click', function () {
                window.onbeforeunload = null;
            })
        });
    }
});
