//json specification table ARRAY
function reportSpecTableSortableChange() {
    jsonSpecTableArraySubmitBtn();
}

let deleteJsonSpecTableRowsBtn = function () {

    const root_card = $(this).parent().parent();
    let sorable_list = $('#spec_items_sortable_list');
    
    //console.log(sorable_list);

    root_card.remove();

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

    //refresh textarea data:
    jsonSpecTableArraySubmitBtnHandler();

};

let editJsonSpecTableRowsBtn = function () {

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

};

const jsonSpecTableSubmitBtn = 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 _title = card.find('.js_title_txt').val();
    let _value = card.find('.js_value_txt').val();

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

    card.find('.json_title_showtext').val(_title);
    card.find('.json_value_showtext').val(_value);

    let obj = {
        title: _title,
        value: _value
    }

    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 jsonSpecTableArraySubmitBtn(event) {

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

};


function jsonSpecTableArraySubmitBtnHandler() {

    let root_of_current = $('.json_handler_spec_table_array');
    let textarea = root_of_current.find('.json_text_area');
    const sortableList = root_of_current.find('#spec_items_sortable_list');

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

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

        const card = $(li);
        let _title = card.find('.js_title_txt').val();
        let _value = card.find('.js_value_txt').val();

        let obj = {
            title: _title,
            value: _value
        };
        if (!li.classList.contains('no-item-found')) {
            arr[i] = obj;
        }
    });

    let stringjs = JSON.stringify(arr);

    textarea.val(stringjs);

};

const jsonSpecTableCancelBtn = function () {

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

};

function jsonSpecTableRowHtmlMacker(json) {
    let htmlRow = "";
    htmlRow += '<div class="json_spec_table_card ng-card-json-item global-json-handler-card">';
    htmlRow += '<div class="json_spec_table_box ng-spec-card">';

    htmlRow += '<div class="my-handle"><i class="ph ph-caret-up-down"></i></div>';
    
    htmlRow += '<div class="textareabox">';
    htmlRow += '<textarea placeholder="عنوان" rows="2" class="js_title_txt form-control">'+ (json != null ? json['title'] : "") +'</textarea>';
    htmlRow += '<textarea placeholder="مقدار" rows="2" class="js_value_txt form-control">'+ (json != null ? json['value'] : "") +'</textarea>';
    htmlRow += '</div>';

    htmlRow += '<button type="button" class="all_json_spec_table_delete_btn btn btn-danger btn-sm"><i class="ph ph-trash"></i></button>';


    htmlRow += '</div>';

    htmlRow += '</div>';

    return htmlRow;
}


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

    //https://stackoverflow.com/a/3273355/4565796
    //$('.json_spec_table_submit_array').click( function() { jsonSpecTableArraySubmitBtn(true,"submit click 2"); });
    $('.json_spec_table_submit').click(jsonSpecTableSubmitBtn);
    $('.json_spec_table_cancel').click(jsonSpecTableCancelBtn);

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

        const jsonString = $.trim($('.json_handler_spec_table_array > textarea').val());
        let jsonSpecTableArrayObj;

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

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

        $('.all_json_spec_table_delete_btn').click(deleteJsonSpecTableRowsBtn);

    }

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

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

        const htmlrow = jsonSpecTableRowHtmlMacker(null);
        root.find(".showbox").find("#spec_items_sortable_list").append(htmlrow);
        $('.all_json_spec_table_delete_btn').click(deleteJsonSpecTableRowsBtn);

    });

    $('#spec_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: reportSpecTableSortableChange
    });

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

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

    });

}); //end of jqury doc ready