define(['jquery', 'core/modal_factory', 'core/templates', 'core/str',
        'local_ned_controller/participationpower', 'theme_boost/popover', 'local_ned_controller/add_sorter'],
    function ($, ModalFactory, Templates, str, PP, Popover, Add_sorter) {
    return {
        init: function () {
            const TABLE_SELECTOR = '#datatable';
            const ROW_SELECTOR = 'tr div.row-toggle';
            const ROW_HIGHLIGHTED_SELECTOR = ROW_SELECTOR + '.highlighted';

            $(document).ready(function () {
                let $datatable = $(TABLE_SELECTOR);

                // add sorter
                if ($datatable.length){
                    // noinspection JSUnusedLocalSymbols
                    let sorter_options = {
                        'textSorter': {
                            // If direction - sort by First name, else sort by Last name
                            '.name': function(a, b, direction, columnIndex, table){

                                const f_sort = (a, b) => a > b ? 1 : (a < b ? -1 : 0);

                                /**
                                 * [first_name, last_name] = divide_name(fullname);
                                 *
                                 * @param {string} name
                                 *
                                 * @returns {string[]}
                                 */
                                function divide_name(name) {
                                    if (!name || !name.length) return ['', ''];

                                    let sep = name.includes('||') ? '||' : ' ';
                                    let name_arr = name.split(sep);

                                    if (name_arr.length < 2) return [name, ''];
                                    else if (name_arr.length === 2) return name_arr;
                                    else return [name_arr.slice(0, -1).join(' '), name_arr.slice(-1)[0]];
                                }

                                let [a_first, a_last] = divide_name(a);
                                let [b_first, b_last] = divide_name(b);

                                if (direction) {
                                    return f_sort(a_first, b_first);
                                } else {
                                    return f_sort(b_last, a_last);
                                }
                            }
                        },
                    }

                    Add_sorter.add_sort(TABLE_SELECTOR, sorter_options);
                }

                // Buttons to highlight rows
                let $complete_course_form = $('#complete_course_form');
                let form_input = $complete_course_form.children().children('[name="complete_course_data"]');
                let $complete_course_select = $("#id_complete_course_select");
                let opt_text = $complete_course_select.html();
                let not_completed_course_users = 0; // counter of selected users, who not complete course

                //init selected users when page is loaded
                function init_not_completed_course_users() {
                    let rows = $datatable.find(ROW_HIGHLIGHTED_SELECTOR);
                    if (!rows) return;

                    rows.each((index, elem) => {
                        let $elem = $(elem);
                        let not_course_completed = !$elem.children('.tt-si-course-completed').length;
                        if (not_course_completed){
                            not_completed_course_users++;
                        }
                        update_course_status_select();
                    });
                }
                function update_course_status_select() {
                    if (not_completed_course_users !== 0){
                        let pass_option = $complete_course_select.find("option[value='3']");
                        if (pass_option.length){
                            pass_option.remove();
                        }
                    } else if (opt_text && opt_text.length){
                        $complete_course_select.html(opt_text);
                    }
                }
                $datatable.delegate(ROW_SELECTOR, 'click', function () {
                    let $elem = $(this);
                    $elem.toggleClass('highlighted');
                    let selected = $elem.parent().parent();
                    selected.toggleClass('highlight');

                    let not_course_completed = !$elem.children('.tt-si-course-completed').length;
                    if (not_course_completed){
                        //checking user selection or deselection
                        let action = this.classList.contains('highlighted') ? 1 : -1;
                        not_completed_course_users += action;
                    }
                    update_course_status_select();
                });

                init_not_completed_course_users();

                $complete_course_select.change(function () {
                    let userid_data = $datatable.find('tr.highlight').map((i, element) => $(element).data('userid')).get();
                    form_input.val(userid_data.join(','));
                    window.onbeforeunload = null;
                    window.confirm = null;
                    $complete_course_form.submit();
                });

                PP.init('a.participationpower');

                // Popover.
                $.fn.tooltip.Constructor.Default.whiteList.a =
                    $.fn.tooltip.Constructor.Default.whiteList.a.concat(['data-cmid', 'data-userid', 'data-action']);
                $("[data-bind='popover']").popover({
                    trigger: "hover",
                    html: true,
                }).on('hide.bs.popover', function () {
                    if ($(".popover:hover").length){
                        return false;
                    }
                });
                $('body').on('mouseleave', '.popover', function () {
                    $('.popover').popover('hide');
                });
            });
        }
    };
});
