/**
 * Copyright 2022 codelug
 * 
 * @author codelug
 * @version 1.0
 */
(function($) {
    'use strict';
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-tooltip="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl, {
            trigger: 'hover'
        });
    });


    $('body').on('click', '[data-bs-toggle="modal"]', function() {
        $($(this).data("bs-target") + ' .modal-dialog').load($(this).data("remote"), function() {

        });
    });
    $('body').on('submit', 'form[data-loader=""]', function(e) {
        $(this).find('button[type="submit"]').html('<span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>');
        $(this).find('button[type="submit"]').prop("disabled", true);
    });
    // Action Control

    $('body').on('click', '.confirm', function() {
        if (confirm(__('Do you want to remove it ?'))) {
            return true;
        } else {
            return false;
        }
    });

    // Cover Select 
    $(document).on('click', '.btn-upload', function() {
        var id = $(this).attr('data-id');
        $('#file-' + id).click();
        return false;
    });

    $(document).on('click', '.btn-clear', function() {
        var id = $(this).attr('data-id');
        $('.' + id).val('');
        $('.ratio-preview').removeClass('d-none');
        $('.' + id).css('background-image', '');
        $('.btn-clear').addClass('d-none');
        return false;
    });
    $(document).on('change', '.ratio-input', function() {
        var id = $(this).attr('data-preview');
        $('.btn-clear').removeClass('d-none');
        if (this.files && this.files[0]) {

            var reader = new FileReader();
            reader.onload = function(e) {
                $('.' + id).css('background-image', 'url(' + e.target.result + ')');
                $('.ratio-preview').addClass('d-none');
            }
            reader.readAsDataURL(this.files[0]);
        }
    });

    // Bootstrap select
    $('.bs-select').selectpicker();

    // Colorpicker
    $('.colorpicker').minicolors({
        control: $(this).attr('data-control') || 'hue',
        inline: $(this).attr('data-inline') === 'true',
        letterCase: 'lowercase',
        opacity: false,
        change: function(hex, opacity) {
            if (!hex) return;
            if (opacity) hex += ', ' + opacity;
            try {
                console.log(hex);
            } catch (e) {}
            $(this).select();
        },
        theme: 'bootstrap'
    });

    // Nav  
    $(document).on('click', '[data-nav] a', function() {
        var $this = $(this),
            $active, $li, $li_li;

        $li = $this.parent();
        $li_li = $li.parents('li');

        $active = $li.closest("[data-nav]").find('.active');

        $li_li.addClass('active');
        ($this.next().is('ul') && $li.toggleClass('active')) || $li.addClass('active');

        $active.not($li_li).not($li).removeClass('active');

        if ($this.attr('href') && $this.attr('href') != '#') {
            $(document).trigger('Nav:changed');
        }
    });

    // Game add type
    $(document).on('change', '[name="type"]', function() {
        var val = $(this).val();
        if (val == 'upload') {
            $('.upload').removeClass('d-none');
            $('.remote').addClass('d-none');
        } else if (val == 'remote') {
            $('.upload').addClass('d-none');
            $('.remote').removeClass('d-none');
        } 
    });
    $('[name="type"]:checked').trigger('change');
    // tool import
    $(document).on('click', '.btn-import', function() {
        $('.ajax-form').each(function() {
            $(this).trigger('submit');
        });
        return false;
    });
    // tool game add
    $(document).on('submit', '.ajax-form', function(e) {
        var postdata = $(this).serializeArray();
        var formurl = $(this).attr("action");
        var dataUrl = $(this).attr("data-url");
        $.ajax({
            url: formurl,
            type: "POST",
            data: postdata,
            success: function(data, textStatus, jqXHR) {
                $('form[data-url="' + dataUrl + '"').remove();
            }
        });
        e.preventDefault();
    });
    // add post
    $('.selectize-collection').selectize({
        valueField: 'id',
        labelField: 'title',
        searchField: 'title',
        options: [],
        maxItems: 1,
        render: {
            option: function(item, escape) {
                return '<div class="d-flex align-items-center px-3 py-1">' +
                    '<div class="ratio ratio-1x1 w-50px bg-img-cover rounded-1" style="background-image:url(' + escape(item.image) + '"></div>' +
                    '<div class="ms-3">' +
                    (item.title ? '<div class="fs-sm fw-semibold">' + escape(item.title) + '</div>' : '') +
                    (item.type ? '<div class="text-muted fs-xs">' + escape(item.type) + '</div>' : '') +
                    '</div>' +
                    '</div>';
            }
        },
        load: function(query, callback) {
            if (!query.length) return callback();
            $.ajax({
                url: Base + '/admin/ajax/posts?q=' + encodeURIComponent(query),
                type: 'GET',
                dataType: 'json',
                error: function() {
                    callback();
                },
                success: function(res) {
                    if (res.data.length > 0 || resp.data) {
                        callback(res.data.slice(0, 10));
                    }
                }
            });
        },
        create: false,
        onChange: function(value) {

            $.ajax({
                url: Base + '/admin/ajax/post?id=' + value,
                type: 'GET',
                dataType: 'json',
                success: function(resp) {
                    var id = $(".row-collection > div").children().length;
                    if(!$('.col-collection[data-id="'+resp.data.id+'"]').length) {
                        $('#empty-collection').tmpl(resp.data).appendTo('.row-collection');
                    }
                }
            });

            $('.selectize-collection')[0].selectize.clear();
        }
    });

    

    // remove
    $('body').on('click', '.remove', function() {
        var id = $(this).attr('data-id');
        var dataType = $(this).attr('data-type');
        if ($(this).data('ajax')) {
            $.ajax({
                type: 'POST',
                url: Base + '/admin/delete/' + dataType + '/' + id,
                success: function(resp) {
                    $('.' + dataType + '-table tbody>tr[data-id="' + id + '"]').remove();
                    if (dataType == 'collection') {
                        $('.col-' + dataType + '[data-id="' + id + '"]').remove();
                    } else {
                        $('.' + dataType + '-table tbody>tr[data-id="' + id + '"]').remove();
                    }
                    Snackbar.show({ text: __('Deletion is successful') });
                }
            });
        } else {
            if (dataType == 'collection') {
                $('.col-' + dataType + '[data-id="' + id + '"]').remove();
            } else {
                $('.' + dataType + '-table tbody>tr[data-id="' + id + '"]').remove();
            }
            Snackbar.show({ text: __('Deletion is successful') });
        }
    });

})(jQuery);