/**
 * Drag-and-drop dish and dish category ordering in WordPress admin.
 */
(function ($) {
    'use strict';

    function showNotice($wrap, message, type) {
        if (!$wrap.length) {
            return;
        }

        $wrap
            .removeClass('notice-success notice-error is-hidden')
            .addClass(type === 'success' ? 'notice-success' : 'notice-error')
            .find('p')
            .text(message);
        $wrap.show();

        var timerKey = $wrap.attr('class') || 'notice';
        window.clearTimeout(showNotice._timers[timerKey]);
        showNotice._timers[timerKey] = window.setTimeout(function () {
            $wrap.fadeOut(200);
        }, 2500);
    }
    showNotice._timers = {};

    function saveDishOrder($list) {
        var cfg = window.macaMenulistDishSort || {};
        var categoryId = $list.data('category-id');
        var dishIds = $list.find('[data-dish-id]').map(function () {
            return $(this).data('dish-id');
        }).get();

        $list.addClass('is-saving');

        return $.post(cfg.ajaxUrl, {
            action: 'maca_reorder_dishes',
            nonce: cfg.nonce,
            category_id: categoryId,
            dish_ids: JSON.stringify(dishIds),
        })
            .done(function (response) {
                if (response && response.success) {
                    showNotice($('.maca-dish-sort-notice'), cfg.saved || 'Order saved.', 'success');
                } else {
                    showNotice($('.maca-dish-sort-notice'), cfg.error || 'Could not save order.', 'error');
                }
            })
            .fail(function () {
                showNotice($('.maca-dish-sort-notice'), cfg.error || 'Could not save order.', 'error');
            })
            .always(function () {
                $list.removeClass('is-saving');
            });
    }

    function saveCategoryOrder($list) {
        var cfg = window.macaMenulistDishCategorySort || {};
        var categoryIds = $list.find('[data-category-id]').map(function () {
            return $(this).data('category-id');
        }).get();

        $list.addClass('is-saving');

        return $.post(cfg.ajaxUrl, {
            action: 'maca_reorder_dish_categories',
            nonce: cfg.nonce,
            category_ids: JSON.stringify(categoryIds),
        })
            .done(function (response) {
                if (response && response.success) {
                    showNotice($('.maca-dish-category-sort-notice'), cfg.saved || 'Order saved.', 'success');
                } else {
                    showNotice($('.maca-dish-category-sort-notice'), cfg.error || 'Could not save order.', 'error');
                }
            })
            .fail(function () {
                showNotice($('.maca-dish-category-sort-notice'), cfg.error || 'Could not save order.', 'error');
            })
            .always(function () {
                $list.removeClass('is-saving');
            });
    }

    $(function () {
        $('.maca-dish-sort-list').sortable({
            handle: '.maca-dish-sort-handle',
            axis: 'y',
            containment: 'parent',
            tolerance: 'pointer',
            update: function () {
                saveDishOrder($(this));
            },
        });

        $('.maca-dish-category-sort-list').sortable({
            handle: '.maca-dish-category-sort-handle',
            axis: 'y',
            items: 'tr',
            tolerance: 'pointer',
            update: function () {
                saveCategoryOrder($(this));
            },
        });
    });
})(jQuery);
