let quizDescAnsOptionsTextAreaSelectorID = null;

function jsonQuizDescAnsRowHtmlMacker(json) {
    let htmlRow = "";
    htmlRow += '<div class="json_quiz_descriptive_answer_card card card-outline card-json-item collapsed-card global-json-handler-card">';
    htmlRow += '<div class="card-header json_quiz_descriptive_answer_box">';
    htmlRow += '<div class="my-handle"><i class="ph ph-caret-up-down"></i></div>';
    htmlRow += '<div class="textcontainer">';
    htmlRow += '<span class="json_quiz_descriptive_answer_showtext" > جواب تشریحی سوال ' + (json != null ? json['q_num'] : "-") + '</span><br>';
    htmlRow += '</div>';
    htmlRow += '<div class="card-tools">';
    htmlRow += '<button type="button" class="json_handler_box_opener_btn btn btn-primary btn-sm"><i class="ph ph-pencil"></i></button>';
    htmlRow += '<button type="button" class="quiz_descriptive_answer_delete_btn btn btn-danger btn-sm"><i class="ph ph-trash"></i></button>';
    htmlRow += '</div>';
    htmlRow += '</div>';
    htmlRow += '<div class="card-body" style="display: none;">';   
    htmlRow += '<textarea style="display:none;" id="quiz_descriptive_answer_options_' + uid() + '" class="js_quiz_descriptive_answer_options top15" rows="3">' + (json != null ? JSON.stringify(json['desc_answer']) : "[]") + '</textarea>';
    htmlRow += '<div class="optionsbox"><span style="margin-left: 20px;">تعداد پاراگرافهای تعریف شده: <span class="ocounter">'+  (json != null ? ( $.isArray(json['desc_answer'])? json['desc_answer'].length : '0' ) : "0")  +'</span></span><button class="btn btn-primary btn-sm quiz_descriptive_answer_options_edit">ویرایش پاراگرافها</button></div>';
    htmlRow += '<br/>';
    htmlRow += '<div class="notes">بخش انتقال به بخش دلخواه امکان انتقال به بخش  جدید را فراهم می کند. چنان چه متن دکمه مربوطه را خالی بگذارید، این قسمت نمایش داده نمی شود.</div>';
    htmlRow += '<span>متن دکمه انتقال به بخش دلخواه: </span><textarea class="js_quiz_descriptive_answer rtl-right" rows="2">' + (json != null ? json['btn_text'] : "") + '</textarea>';
    htmlRow += '<br/>';

    let intentType = (json != null ? json['intent_type'] : "-");
    let intentData = (json != null ? json['intent_data'] : "-");
    htmlRow += intentInputHtmlGenerator(intentType,intentData,"xxxx_type","xxxx_data");

    htmlRow += '<span class="minitext">بعد از ایجاد تغییرات بروی این آیتم، بروی ثبت تغییرات کلیک کنید. دقت کنید ثبت تغییرات به معنی ذخیره در سرور نمیباشد</span>';
    htmlRow += '<div class="local_submit_parent">';
    htmlRow += '<span class="json_quiz_descriptive_answer_submit_array btn btn-primary btn-sm">ثبت تغییرات</span>';
    htmlRow += '<span class="json_quiz_descriptive_answer_cancel btn btn-gray btn-sm">انصراف</span>';
    htmlRow += '</div>';
    htmlRow += '</div>';
    htmlRow += '</div>';

    return htmlRow;

}

function jsonQuizDescAnsOptionRowHtmlMacker(json) {
    let htmlRow = "";
    htmlRow += '<div class="json_quiz_descriptive_answer_option_card card card-outline card-json-item collapsed-card global-json-handler-card">';
    htmlRow += '<div style="text-align:right" class="card-header json_quiz_descriptive_answer_option_box">';
    htmlRow += '<div class="my-handle"><i class="ph ph-caret-up-down"></i></div>';
    htmlRow += '<div style="display:inline-block;" class="sorttextcontainer">';
    htmlRow += '<span class="json_quiz_descriptive_answer_option_showtext" >' + (json != null ? json['answer_text'] : "-") + '</span><br>';
    htmlRow += '</div>';
    htmlRow += '<div class="card-tools">';
    htmlRow += '<button type="button" class="json_handler_box_opener_btn btn btn-primary btn-sm"><i class="ph ph-pencil"></i></button>';
    htmlRow += '<button type="button" class="quiz_descriptive_answer_options_delete_btn btn btn-danger btn-sm"><i class="ph ph-trash"></i></button>';
    htmlRow += '</div>';
    htmlRow += '</div>';
    htmlRow += '<div class="card-body" style="display: none;text-align:right;">';
    htmlRow += '<span>متن پاراگراف جواب تشریحی: </span><textarea class="js_quiz_descriptive_answer_answer_text rtl-right" rows="2">' + (json != null ? json['answer_text'] : "") + '</textarea>';
    
    let no_image_style = 'style="display:none"';
    let has_image_style = '';
    let json_image_url = json != null ? json['answer_image'] : "";
    if(json_image_url == ""){
        no_image_style = '';
        has_image_style = 'style="display:none"';
    }
    let imgClass = 'js_quiz_descriptive_answer_answer_image';
    //let counter = json['id'];
    let counter = randomUID(21);
    htmlRow += '<span>تصویر / گیف برای پاراگراف: </span><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 += '<span class="minitext">بعد از ایجاد تغییرات، بروی ثبت تغییرات کلیک کنید. دقت کنید ثبت تغییرات به معنی ذخیره در سرور نمیباشد</span>';
    htmlRow += '<div class="local_submit_parent">';
    htmlRow += '<span class="json_quiz_descriptive_answer_option_submit_array btn btn-primary btn-sm">ثبت تغییرات</span>';
    htmlRow += '<span class="json_quiz_descriptive_answer_option_cancel btn btn-gray btn-sm">انصراف</span>';
    htmlRow += '</div>';
    htmlRow += '</div>';
    htmlRow += '</div>';

    return htmlRow;

}

const jsonQuizDescAnsCancelBtn = function () {

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

};

const jsonQuizDescAnsOptionCancelBtn = function () {

    //let root_of_current = $(this).parent().parent().parent().parent().parent();
    let card = $('.json_handler_quiz_descriptive_answer_options_array').find('.json_quiz_descriptive_answer_option_card');
    //root_of_current.find('.json_handler_box_opener_btn').show();
    card.find('.json_handler_box_opener_btn').show();
    card.addClass("collapsed-card");
    let card_body = card.find('.card-body');
    card_body.slideUp();

};

const deleteQuizDescAnsRowsBtn = 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();
            
            //refresh textarea data:
            jsonQuizDescAnsArraySubmitBtnHandler(false,null);

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

        }

    })


};

const deleteQuizDescAnsOptionsRowsBtn = 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_quiz_descriptive_answer_options_array").find(".showbox").find("#sorable_list").html(htmlrow);
            }

        }

    })


};

function jsonQuizDescAnsArraySubmitBtn(event) {

    let submitFromSingleCard = event.data.submitFromSingleCard;

    //https://stackoverflow.com/a/9467172/4565796
    let card = $(this).parent().parent().parent();
    jsonQuizDescAnsArraySubmitBtnHandler(submitFromSingleCard,card);

};


function jsonQuizDescAnsArraySubmitBtnHandler(submitFromSingleCard,card) {

    let root_of_current = $('.json_handler_quiz_descriptive_answer_array');
    let textarea = root_of_current.find('.json_text_area');
    const sortableList = root_of_current.find('#sorable_list');
    root_of_current.find('.json_handler_box_opener_btn').show();

    if(submitFromSingleCard){
        //something in a single card changed! so update card header and close current card
        card.addClass("collapsed-card");
        let card_body = card.find('.card-body');
        card_body.slideUp();
    }

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

        let qnumber = i+1;

        const card = $(li);
        let _btn_text    = card.find('.js_quiz_descriptive_answer').val();
        let _intent_type = card.find('.intent_type_code_input').val();
        let _intent_data = card.find('.js_quiz_descriptive_answer_intent_data').val();
        let _desc_answer = card.find('.js_quiz_descriptive_answer_options').val();

        let obj = {
            q_num      : qnumber,
            btn_text   : _btn_text,
            intent_type: _intent_type,
            intent_data: _intent_data,
            desc_answer: JSON.parse(_desc_answer)
        };
        if(!li.classList.contains('no-item-found')){
            arr[i] = obj;
        }
    });



    let stringjs = JSON.stringify(arr);

    //console.log("quiz_q json = " + stringjs);

    textarea.val(stringjs);


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

};


function jsonQuizDescAnsOptionArraySubmitBtn(event) {

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

};


function jsonQuizDescAnsOptionArraySubmitBtnHandler(submitFromSingleCard,card) {

    let root_of_current = $('.json_handler_quiz_descriptive_answer_options_array');
    let textarea = root_of_current.find('.json_text_area');
    const sortableList = root_of_current.find('#sorable_list');
    root_of_current.find('.json_handler_box_opener_btn').show();

    if(submitFromSingleCard){
        //something in a single card changed! so update card header and close current card
        let _answer_text = card.find('.js_quiz_descriptive_answer_answer_text').val();
        card.find('.json_quiz_descriptive_answer_option_showtext').html(_answer_text);
        card.addClass("collapsed-card");
        let card_body = card.find('.card-body');
        card_body.slideUp();
    }

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

        const card = $(li);
        let _answer_text = card.find('.js_quiz_descriptive_answer_answer_text').val();
        let _answer_image = card.find('.js_quiz_descriptive_answer_answer_image').val();

        let obj = {
            answer_text: _answer_text,
            answer_image: _answer_image
        };
        if(!li.classList.contains('no-item-found')){
            arr[i] = obj;
        }
    });



    let stringjs = JSON.stringify(arr);

    //console.log("quiz_q json = " + stringjs);

    textarea.val(stringjs);


    notyf.open({
        type: 'info',
        message: 'تغییرات پاراگرافهای پاسخ ثبت شد'
    });

};



const quizDescAnsOptionsEditBtn = function () {

    

    let root_of_current = $(this).parent().parent(); //card body
    let options_textarea = root_of_current.find('.js_quiz_descriptive_answer_options');
    quizDescAnsOptionsTextAreaSelectorID = options_textarea.attr('id');

    let json = options_textarea.val();
    //todo: open dialog
    //alert('test: ' + quizOptionsTextAreaSelectorID);

    jsonArray = JSON.parse(json);

    htmlToShow = '';
    htmlToShow += '<div class="fancybox_scrollbox">';
    htmlToShow += '<div class="json_handler_quiz_descriptive_answer_options_array">';
    htmlToShow += '<textarea style="display:none" class="form-control json_text_area" rows="2">' + json + '</textarea>';
    htmlToShow += '<div style="text-align:right"><span class="bold" style="margin-left:15px">مدیریت پاراگرافهای پاسخ</span><button id="add_json_quiz_descriptive_answer_option_array_item" class="btn btn-sm btn-primary top15 bottom15">افزودن پاراگراف جدید</button></div>';
    htmlToShow += '<div class="showbox">';
    htmlToShow += '<div id="sorable_list" class="list-group col">';

    if (jsonArray.length == 0) {
        const htmlrow = ThereIsNoRowHereHtml();
        htmlToShow += htmlrow;
    } else {
        $.each(jsonArray, function (key, value) {
            const htmlrow = jsonQuizDescAnsOptionRowHtmlMacker(value);
            htmlToShow += htmlrow;
        });
    }

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

    htmlToShow += '<div style="text-align:right"><button id="json_quiz_descriptive_answer_options_sort_submit" class="btn btn-sm btn-primary top15">ثبت ترتیب</button></div>';

    htmlToShow += '<div style="text-align:left"><button id="json_quiz_descriptive_answer_options_finish" class="btn btn-sm btn-primary top25">ثبت تغییرات پاراگرافهای پاسخ</button></div>';


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

    htmlToShow += '';
    htmlToShow += '';
    htmlToShow += '';
    



    $.fancybox.open(
        htmlToShow,
        {
            touch: false,
            afterShow : () => {
                
                $('.fancybox_scrollbox #sorable_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'
                });

                //init sort btn
                $('#json_quiz_descriptive_answer_options_sort_submit').click({submitFromSingleCard:false},jsonQuizDescAnsOptionArraySubmitBtn);


                //all inits of quiz options
                $('.json_handler_box_opener_btn').click(jsonHandlersBoxOpener);
                $('.quiz_descriptive_answer_options_delete_btn').click(deleteQuizDescAnsOptionsRowsBtn);
                $('.json_quiz_descriptive_answer_option_submit_array').off("click");
                //https://stackoverflow.com/a/9467172/4565796
                $('.json_quiz_descriptive_answer_option_submit_array').click({submitFromSingleCard:true},jsonQuizDescAnsOptionArraySubmitBtn);
                $('.json_quiz_descriptive_answer_option_cancel').click(jsonQuizDescAnsOptionCancelBtn);
                $('.mppanel_image_url').on("input", changeImagePreview);    
                $('#add_json_quiz_descriptive_answer_option_array_item').click(quizAddDescAnsOptionRow);
                newGenImageHandler();
                
                $('#json_quiz_descriptive_answer_options_finish').click(function () {

                    //refresh fancybox textarea data:
                    jsonQuizDescAnsOptionArraySubmitBtnHandler(false,null);

                    //get options json to transfer
                    let dataToTransfer = $('.json_handler_quiz_descriptive_answer_options_array').find('.json_text_area').val();

                    let parentOptionsTextarea = $('#' + quizDescAnsOptionsTextAreaSelectorID);
                    

                    //refresh options count:
                    const ocount = JSON.parse(dataToTransfer);
                    parentOptionsTextarea.parent().find('.optionsbox').find('.ocounter').html(ocount.length);

                    //transfer data:
                    parentOptionsTextarea.val(dataToTransfer);

                    $.fancybox.close();

                    
                });


                


            }
        }
    );


};





const quizAddDescAnsOptionRow = function () {

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

    const htmlrow = jsonQuizDescAnsOptionRowHtmlMacker(null);
    root.find(".showbox").find("#sorable_list").prepend(htmlrow);

    $('.json_handler_box_opener_btn').click(jsonHandlersBoxOpener);
    $('.quiz_descriptive_answer_options_delete_btn').click(deleteQuizDescAnsOptionsRowsBtn);
    $('.json_quiz_descriptive_answer_option_submit_array').off("click");
    //https://stackoverflow.com/a/9467172/4565796
    $('.json_quiz_descriptive_answer_option_submit_array').click({submitFromSingleCard:true},jsonQuizDescAnsOptionArraySubmitBtn);
    $('.json_quiz_descriptive_answer_option_cancel').click(jsonQuizDescAnsOptionCancelBtn);
    $('.mppanel_image_url').on("input", changeImagePreview);     
    newGenImageHandler();

}



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



    //Quiz Descriptive Answer Part: (Json Handler)

    //https://stackoverflow.com/a/3273355/4565796

    if ($(".json_handler_quiz_descriptive_answer_array")[0]) { //there is json quiz_descriptive_answer array list:

        const jsonString = $.trim($('.json_handler_quiz_descriptive_answer_array > textarea').val());
        let jsonQuizDescAnsArrayObj;

        if (jsonString == '') {
            jsonQuizDescAnsArrayObj = [];

        } else {
            jsonQuizDescAnsArrayObj = JSON.parse(jsonString);
        }

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

        $('.json_handler_box_opener_btn').click(jsonHandlersBoxOpener);
        $('.quiz_descriptive_answer_delete_btn').click(deleteQuizDescAnsRowsBtn);
        $('.json_quiz_descriptive_answer_submit_array').off("click");
        //https://stackoverflow.com/a/9467172/4565796
        $('.json_quiz_descriptive_answer_submit_array').click({submitFromSingleCard:true},jsonQuizDescAnsArraySubmitBtn);
        $('.json_quiz_descriptive_answer_cancel').click(jsonQuizDescAnsCancelBtn);
        $('.intent_type_change_btn').click(selectIntentDialog);
        $('.intent_data_change_btn').click(editIntentDataSelector);
        //$('.intent_data_help_btn').click(showIntentDataHelper);
        //$('.intent_type_code_input').each(intentNamesPrinter);
        $('.intent_type_code_input').each(function (){intentNamesPrinter($(this));});
        $('.mppanel_image_url').on("input", changeImagePreview);

    }




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

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

        const htmlrow = jsonQuizDescAnsRowHtmlMacker(null);
        root.find(".showbox").find("#sorable_list").prepend(htmlrow);

        $('.json_handler_box_opener_btn').click(jsonHandlersBoxOpener);
        $('.quiz_descriptive_answer_delete_btn').click(deleteQuizDescAnsRowsBtn);
        $('.json_quiz_descriptive_answer_submit_array').off("click");
        //https://stackoverflow.com/a/9467172/4565796
        $('.json_quiz_descriptive_answer_submit_array').click({submitFromSingleCard:true},jsonQuizDescAnsArraySubmitBtn);
        $('.json_quiz_descriptive_answer_cancel').click(jsonQuizDescAnsCancelBtn);
        $('.intent_type_change_btn').click(selectIntentDialog);
        $('.intent_data_change_btn').click(editIntentDataSelector);
        //$('.intent_data_help_btn').click(showIntentDataHelper);
        //$('.intent_type_code_input').each(intentNamesPrinter);
        $('.intent_type_code_input').each(function (){intentNamesPrinter($(this));});
        $('.mppanel_image_url').on("input", changeImagePreview);
        $('.quiz_descriptive_answer_options_edit').click(quizDescAnsOptionsEditBtn);


    });


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

    //init
    $('.quiz_descriptive_answer_options_edit').click(quizDescAnsOptionsEditBtn);




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

        let sendData = {
            id: $.trim($('#id').val()),
            descriptive_answers: $.trim($('#descriptive_answers').val())
        }

        RequestSuperHandler(
            $(this), //Current Obj
            'آیا از ذخیره تغییرات پاسخهای تشریحی بروی سرور مطمئنید؟', //Alert Title
            "", //Alert Desc
            1, // alertType -> 1:confirm - 2:delete
            '/update_quiz_descriptive_answer', //Request URL
            "", //Return URL
            sendData
        );

    });



    //end of QUIZ Descriptive Answer






    
}); //end of jqury doc ready