//json gallery ARRAY

function reportGalleryItemsSortableChange() {
    jsonGalleryItemsArraySubmitBtn();
}

function jsonGalleryItemsArraySubmitBtn(event) {

    //https://stackoverflow.com/a/9467172/4565796
    //IsSingleItemEdit = event.data.IsSingleItemEdit;
    //let card = $(this).parent().parent().parent();
    jsonGalleryArraySubmitBtnHandler();

};

const deleteJsonGalleryRowsBtn = function () {

    const root_card = $(this).parent().parent().parent();
    const sorable_list = $(this).parent().parent().parent().parent();

    Swal.fire({
        title: 'این آیتم را حذف میکنید؟',
        icon: '',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#007bff',
        confirmButtonText: 'حذف آیتم',
        cancelButtonText: 'انصراف'
    }).then((result) => {
        if (result.isConfirmed) {

            root_card.remove();

            if (sorable_list.children().length == 0) {
                const htmlrow = ThereIsNoRowHereHtml();
                $(".json_handler_gallery_array").find(".showbox").find("#gallery_items_sortable_list").html(htmlrow);
            }

            //refresh textarea data:
            jsonGalleryArraySubmitBtnHandler();

        }

    })


};



let editJsonGalleryRowsBtn = function () {

    let root_card = $(this).parent().parent().parent();
    root_card.find('.card-body').show('slideDown');
    $(this).hide();

};



const jsonGallerySubmitBtn = function () {

    let root_of_current = $(this).parent().parent().parent().parent().parent().parent();
    let textarea = root_of_current.find('.json_text_area');
    let card = $(this).parent().parent().parent();

    let _img = card.find('.js_gallery_img').val();

    root_of_current.find('.all_json_gallery_edit_btn').show();

    card.find('.json_gallery_showimg').attr("src", _img);

    let obj = {
        img: _img
    }

    let stringjs = JSON.stringify(obj);

    textarea.val(stringjs);

    card.addClass("collapsed-card");
    let card_body = card.find('.card-body');
    card_body.slideUp();

    notyf.open({
        type: 'info',
        message: 'تغییرات ثبت شد'
    });
};

function jsonGalleryArraySubmitBtn(event) {

    //https://stackoverflow.com/a/9467172/4565796
    //IsSingleItemEdit = event.data.IsSingleItemEdit;
    //let card = $(this).parent().parent().parent();
    jsonGalleryArraySubmitBtnHandler();

};


function jsonGalleryArraySubmitBtnHandler() {

    let root_of_current = $('.json_handler_gallery_array');
    let textarea = root_of_current.find('.json_text_area');
    const sortableList = root_of_current.find('#gallery_items_sortable_list');

    root_of_current.find('.all_json_gallery_edit_btn').show();

    let arr = [];
    sortableList.children().each(function (i, li) {

        const card = $(li);
        let _img = card.find('.js_gallery_img').val();

        let obj = {
            url: _img
        };
        if (!li.classList.contains('no-item-found')) {
            arr[i] = obj;
        }
    });

    let stringjs = JSON.stringify(arr);

    //console.log("ss = "+stringjs);

    textarea.val(stringjs);

    // notyf.open({
    //     type: 'info',
    //     message: 'تغییرات آرایه ای ثبت شد'
    // });

};

const jsonGalleryCancelBtn = function () {

    let root_of_current = $(this).parent().parent().parent().parent().parent();
    let card = root_of_current.find('.json_gallery_card');
    root_of_current.find('.all_json_gallery_edit_btn').show();
    card.addClass("collapsed-card");
    let card_body = card.find('.card-body');
    card_body.slideUp();

};

function jsonGalleryRowHtmlMacker(json) { //dont use ids because ids cant be repeated in DOM
    let htmlRow = "";
    htmlRow += '<div class="json_gallery_card card card-outline global-json-handler-card">';

    htmlRow += '<div class="card-body">';

    let no_image_style = 'style="display:none"';
    let has_image_style = '';
    let json_image_url = json != null ? json['url'] : "";
    if(json_image_url == ""){
        no_image_style = '';
        has_image_style = 'style="display:none"';
    }
    let imgClass = 'js_gallery_img';
    //let counter = json['id'];
    let counter = randomUID(21);
    htmlRow += '<div class="image_url_box super-file-select-box""><input id="cat-image-' + counter + '" type="text" class="'+imgClass+' form-control ltr mppanel_image_url" value="' + json_image_url + '">';
    htmlRow += '<div class="sfsb-wrapper">';
    htmlRow += '<div class="section-right"><div '+has_image_style+' class="image-wrapper"><a class="img-preview-a" target="_blank" href="'+json_image_url+'"><img class="img-preview" src="'+json_image_url+'"/></a></div><div '+no_image_style+' class="dropzone general_file_dropzone"></div></div>';
    htmlRow += '<div class="section-left"><span class="ffwrapper">فرمت‌های مورد قبول:<br><span class="fileformats">.png,.gif,.jpg,.jpeg,.webp</span></span><span '+has_image_style+' class="btn-remove-image">حذف و انتخاب مجدد</span><span '+no_image_style+' class="btn-select-image">انتخاب از مدیریت فایل</span></div>';
    htmlRow += '</div>';
    htmlRow += '</div>';

    htmlRow += '<div class="gji-actions">';
    htmlRow += '<div class="my-handle"><i class="ph ph-arrows-out-cardinal"></i></div>';
    htmlRow += '<button type="button" class="all_json_gallery_delete_btn btn edit-small-btn2 btn-danger-light"><i class="ph ph-trash"></i></button>';
    htmlRow += '</div>';

    htmlRow += '</div>';
    htmlRow += '</div>';

    return htmlRow;
}


$(function () { // start of document ready:

    //https://stackoverflow.com/a/3273355/4565796
    //$('.json_gallery_submit_array').click( function() { jsonGalleyItemsArraySubmitBtn(true,"submit click 2"); });
    $('.json_gallery_submit').click(jsonGallerySubmitBtn);
    $('.json_gallery_cancel').click(jsonGalleryCancelBtn);

    if ($(".json_handler_gallery_array")[0]) { //there is json type 1 array list:

        const jsonString = $.trim($('.json_handler_gallery_array > textarea').val());
        let jsonGalleryArrayObj;

        if (jsonString == '') {
            jsonGalleryArrayObj = [];
        } else {
            jsonGalleryArrayObj = JSON.parse(jsonString);
        }

        if (jsonGalleryArrayObj.length == 0) {
            const htmlrow = ThereIsNoRowHereHtml();
            $(".json_handler_gallery_array").find(".showbox").find("#gallery_items_sortable_list").html(htmlrow);
        } else {
            $.each(jsonGalleryArrayObj, function (key, value) {
                //console.log("vs: " + value);
                const htmlrow = jsonGalleryRowHtmlMacker(value);
                $(".json_handler_gallery_array").find(".showbox").find("#gallery_items_sortable_list").append(htmlrow);
            });
        }

        $('.all_json_gallery_edit_btn').click(editJsonGalleryRowsBtn);
        $('.all_json_gallery_delete_btn').click(deleteJsonGalleryRowsBtn);
        $('.json_gallery_submit_array').off("click");
        //https://stackoverflow.com/a/9467172/4565796
        $('.json_gallery_submit_array').click({
            IsSingleItemEdit: true
        }, jsonGalleryArraySubmitBtn);
        $('.json_gallery_cancel').click(jsonGalleryCancelBtn);
        $('.mppanel_image_url').on("input", changeImagePreview);
        newGenImageHandler();

    }

    $('#add_gallery_array_item').click(function () {

        const root = $(this).parent().parent();
        root.find('.no-item-found').remove();

        const htmlrow = jsonGalleryRowHtmlMacker(null);
        root.find(".showbox").find("#gallery_items_sortable_list").append(htmlrow);

        $('.all_json_gallery_edit_btn').click(editJsonGalleryRowsBtn);
        $('.all_json_gallery_delete_btn').click(deleteJsonGalleryRowsBtn);
        $('.json_gallery_submit_array').off("click");
        //https://stackoverflow.com/a/9467172/4565796
        $('.json_gallery_submit_array').click({
            IsSingleItemEdit: true
        }, jsonGalleryArraySubmitBtn);
        $('.mppanel_image_url').on("input", changeImagePreview);
        newGenImageHandler();

    });

    //when save sort click, just submit all childs:
    //https://stackoverflow.com/a/9467172/4565796
    $('#save_gallery_array_sort').click({
        IsSingleItemEdit: false
    }, jsonGalleryArraySubmitBtn);


    $('#gallery_items_sortable_list').sortable({
        group: 'list',
        animation: 200,
        delay: 100, // time in milliseconds to define when the sorting should start
        delayOnTouchOnly: true, // only delay if user is using touch
        handle: ".my-handle", // Drag handle selector within list items
        ghostClass: 'ghost',
        onSort: reportGalleryItemsSortableChange
    });

    $('#pp_gallery_save').click(function () {

        jsonGalleryArraySubmitBtnHandler();
        Swal.fire({
            title: 'از ذخیره گالری محصول فروشگاهی مطمئن هستید؟',
            text: '',
            icon: '',
            showCancelButton: true,
            confirmButtonColor: '#007bff',
            cancelButtonColor: '#909090',
            confirmButtonText: 'بله',
            cancelButtonText: 'انصراف'
        }).then((result) => {
            if (result.isConfirmed) {

                SavePhysicalProductGallery();

            }
        })

    });   


}); //end of jqury doc ready