function rebuildFormOptionsJson(){

    let fieldType = $("#sortable_field_form_select_options_list").data('field-type');

    let newData = [];
    let index = 0;
    $("#sortable_field_form_select_options_list").children('div').each(function () {

        if(fieldType == "checkbox2" || fieldType == "select2"){
            let item_code = $(this).find(".form-option-item-code").val();
            let text = $(this).find(".form-option-title").val();
            let cond_val = $(this).find(".form-option-cond-val").val();
            newData[index] = {
                "item_code" : item_code,
                "text" : text,
                "cond_val" : cond_val
            };
        }else{
            let val = $(this).find(".form-option-title").val();
            newData[index] = val;
        }
        index++;

    });

    $("#val_data").val(JSON.stringify(newData));

}

function FormInnerOptionsListMotherAction(){

    if($('#sortable_field_form_select_options_list')[0]){

        let formOptionsList = $('#sortable_field_form_select_options_list');
        let fieldType = formOptionsList.data('field-type');
        let hideCondVal = "display:none;";
        if(fieldType == "checkbox2" || fieldType == "select2"){
            hideCondVal = "";
        }

        let bigJson = $('#val_data').val();

        if((!bigJson) || (bigJson.trim() == '') || (bigJson.trim() == "") ||
            (bigJson.trim() == "null") || (bigJson.trim() == "undefined") ||
            (bigJson.trim() == null)){
                bigJson = "[]";
            }
    
        let optionsJson = JSON.parse(bigJson);
        let item_index = 0;
        let html = '';

        $('#sortable_field_form_select_options_list').empty();

        optionsJson.forEach(function(option) {

            let option_item_code = "";
            let option_title = "";
            let option_cond_val = "";
            if(fieldType == "checkbox2" || fieldType == "select2"){
                option_item_code = option['item_code'];
                option_title = option['text'];
                option_cond_val = option['cond_val'];
            }else{
                option_title = option;
            }

            html += '<div class="ar-form-options-item">';
            html += '<div class="form-options-items-inner rtl">';

            html += '<div class="fii-data">';
            html += '<div class="my-handle"><i class="ph ph-caret-up-down"></i></div>';
            html += '<textarea style="display:none" rows="1" type="text" class="form-control rtl form-option-item-code">'+option_item_code+'</textarea>';
            html += '<textarea rows="1" type="text" placeholder="تیتر گزینه" class="form-control rtl form-option-title">'+option_title+'</textarea>';
            html += '<input type="number" style="'+hideCondVal+'" placeholder="مقدار شرطی" class="form-control rtl form-option-cond-val" value="'+option_cond_val+'">';
            html += '</div>';

            html += '<div class="fii-tools">';
            html += '<button type="button" class="delete_select_option_json_field btn edit-small-btn3 btn-danger-light2" data-field-type="'+fieldType+'"><i class="ph ph-trash"></i></button>';
            html += '</div>';

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

            item_index = item_index+1;
            
        });

        $('#sortable_field_form_select_options_list').append(html);

    }
}

function formOptionAddNewEmptyItem(fieldType){

    $("#val_data").val();

    let bigJson = $('#val_data').val();
    if((!bigJson) || (bigJson.trim() == '') || (bigJson.trim() == "") ||
        (bigJson.trim() == "null") || (bigJson.trim() == "undefined") ||
        (bigJson.trim() == null)){
            bigJson = "[]";
        }
    let optionsJson = JSON.parse(bigJson);
    
    if(fieldType == "checkbox2" || fieldType == "select2"){
        optionsJson.push(
            {
                "item_code": "ofi"+randomUID(21),
                "text": "",
                "cond_val": ""
            }
        );
    }else{
        optionsJson.push(""); //normal select and checkboxs (only text)
    }
    
    
    //console.log(JSON.stringify(optionsJson));
    $("#val_data").val(JSON.stringify(optionsJson));
    FormInnerOptionsListMotherAction();
    reInitFormOptionsListeners();

}

function reInitFormOptionsListeners() {

    $('.delete_select_option_json_field').click(function () {
        Swal.fire({
            title: 'از حذف این گزینه مطمئن هستید؟',
            text: '',
            icon: '',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#007bff',
            confirmButtonText: 'حذف فیلد',
            cancelButtonText: 'انصراف'
        }).then((result) => {
            if (result.isConfirmed) {
                $(this).parent().parent().parent().remove();
                rebuildFormOptionsJson();
            }
        })
    });

    $('.ar-form-options-item').find('input, textarea').on('input change',rebuildFormOptionsJson);

}

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

    FormInnerOptionsListMotherAction();
    reInitFormOptionsListeners();
        
    $('#sortable_field_form_select_options_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: rebuildFormOptionsJson
    });

    $('.non_text_new_option_save').click(function () {
        let fieldType = $(this).data('type');
        //console.log("fieldType:" + fieldType);
        formOptionAddNewEmptyItem(fieldType);
    });


}); //end of jqury doc ready