

// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR
// WILL DEPRECATED AFTER QUILL EDITOR




let selectionStartIndex = null;
let selectionEndIndex = null;

function jsonSpanRowHtmlMacker(json, name, index) { //dont use ids because ids cant be repeated in DOM

    let htmlRow = "";
    htmlRow += '<div class="json_span_card card card-outline card-json-item collapsed-card global-json-handler-card">';
    htmlRow += '<div class="card-header json_type1_box">';
    htmlRow += '<div class="my-handle"><i class="ph ph-caret-up-down"></i></div>';
    htmlRow += '<div style="max-width: 80%;" class="textcontainer">';
    let headerData;
    if (json != null) {
        let weight = "400";
        if (json['bold'] == 1) weight = "600";
        let decor = "none";
        if (json['underline'] == 1) decor = "underline";
        headerData = '<span class="span_text" style="color:' + json['color'] + ';font-weight:' + weight + ';text-decoration:' + decor + '">' + name + '</span>' + ' <span class="minibox span_intent">' + getIntentName(json['intent_type']) + '</span>';
    } else {
        headerData = '<span class="span_text">' + "--" + '</span>' + ' <span class="minibox span_intent"></span>';
    }
    htmlRow += '<span class="json_span_showrow" >' + headerData + '</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" data-index="' + index + '" class="delete_span 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 += '<div class="row">';
    htmlRow += '<div class="col-md-4">';
    htmlRow += '<span>Bold: </span><select class="span_bold_select form-control form-control-inline"><option ' + (json != null ? (json['bold'] == 1 ? "selected" : "") : "") + ' value="1">روشن</option><option ' + (json != null ? (json['bold'] == 0 ? "selected" : "") : "") + ' value="0">خاموش</option></select>';
    htmlRow += '</div>';
    htmlRow += '<div class="col-md-4">';
    htmlRow += '<span>Underline: </span><select class="span_underline_select form-control form-control-inline"><option ' + (json != null ? (json['underline'] == 1 ? "selected" : "") : "") + ' value="1">روشن</option><option ' + (json != null ? (json['underline'] == 0 ? "selected" : "") : "") + ' value="0">خاموش</option></select>';
    htmlRow += '</div>';
    htmlRow += '<div class="col-md-4">';
    htmlRow += '<span>Oversized: </span><select class="span_oversized_select form-control form-control-inline"><option ' + (json != null ? (json['size'] == 1 ? "selected" : "") : "") + ' value="1">روشن</option><option ' + (json != null ? (json['size'] == 0 ? "selected" : "") : "") + ' value="0">خاموش</option></select>';
    htmlRow += '</div>';
    htmlRow += '</div>';

    htmlRow += '<div style="margin-top:12px" class="row">';
    htmlRow += '<div class="col-md-6">';
    htmlRow += '<div class="color_selector_box pickr-container">رنگ: <input id="span_color' + uid() + '" type="text" class="span_color form-control ltr width76 mppanel_color_forms" value="' + (json != null ? json['color'] : "") + '"><span class="color_box" style="background:' + (json != null ? json['color'] : "") + '"></span></div>';
    htmlRow += '</div>';
    htmlRow += '<div class="col-md-6">';
    htmlRow += '<span>قابل کلیک: </span><select class="clickable_select form-control form-control-inline"><option ' + (json != null ? (json['intent_type'] != 0 ? "selected" : "") : "") + ' value="1">بله</option><option ' + (json != null ? (json['intent_type'] == 0 ? "selected" : "") : "") + ' value="0">خیر</option></select>';
    htmlRow += '</div>';
    htmlRow += '</div>';


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


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

    return htmlRow;

}

const ClickableSelectChanged = function () {
    if ($(this).val() == '1') {
        $(this).parent().parent().parent().find(".span_intent_box").slideDown();
    } else {
        $(this).parent().parent().parent().find(".span_intent_box").slideUp();
        $(this).parent().parent().parent().find(".json_span_intent_type").val('0');
    }
};

const jsonSpanCancelBtn = function () {

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

};


function jsonSpanArraySubmitBtn(event) {

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

};


function jsonSpanArraySubmitBtnHandler(IsSingleItemEdit, card) {

    let root_of_current = $('.paragraph_spans_handler');
    let textarea = root_of_current.find('.paragraph_spans_text_area');
    const sortableList = root_of_current.find('#spans_sortable_list');

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

        let obj = {};
        const card = $(li);

        obj['color'] = card.find(".span_color").val();
        obj['bold'] = card.find(".span_bold_select").val();
        obj['underline'] = card.find(".span_underline_select").val();
        obj['size'] = card.find(".span_oversized_select").val();
        obj['intent_type'] = card.find(".json_span_intent_type").val();
        obj['intent_data'] = card.find(".json_span_intent_data").val();

        arr[index] = obj;
        index++;

        //set preview
        card.find('.json_span_showrow > .span_intent').text(getIntentName(card.find(".json_span_intent_type").val()));

    });

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

    //if we edit only single row and submiting it:
    if (IsSingleItemEdit) {
        card.addClass("collapsed-card");
        let card_body = card.find('.card-body');
        card_body.slideUp();
    }



    let stringjs = JSON.stringify(arr, null, 2);
    //console.log("ss = "+stringjs);
    textarea.val(stringjs);

    updatePreview();

    reGenerateSpansHtmlByJson();

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

};


function reportSpansSortableChange() {
    jsonSpanArraySubmitBtnHandler(false, null);
}

function deleteSpanFunction (){

    let deleteBtn = $(this);
    let indexToDelete = $(this).data('index');
    //console.log("indexToDelete" + indexToDelete);

    Swal.fire({
        title: 'از حذف گرافیک و عملکرد این اسپن مطمئنید؟',
        text: '',
        icon: '',
        showCancelButton: true,
        confirmButtonColor: '#EB052E',
        cancelButtonColor: '#909090',
        confirmButtonText: 'حذف',
        cancelButtonText: 'انصراف'
    }).then((result) => {
        if (result.isConfirmed) {

            let newData = "";

            let regex = new RegExp('\\[span\\]\\[\\[\\*([\\s\\S]+?)\\*\\]\\]', 'g');
            let string = $('#text_data').val();
            let index = 0;
            let stringStartIndex = 0;
            let stringEndIndex = string.length;
            
            while ((match = regex.exec(string)) != null) {

                //for (let i = 0; i < match.length; i++) {
                    //console.log("test: " + match[i]);
                    //match has 2 item, first is with regex pattern ( example: [span][[*سلام*]] )
                    // and second is just String ( example: سلام )
                //}

                let matchStart = (match.index);
                let matchEnd = (match.index + match[0].length);
                
                if(index == indexToDelete){
                    //delete span:
                    newData += string.substring(stringStartIndex,matchStart);
                    newData += match[1]; // raw string of match
                    stringStartIndex = matchEnd;
                }else{
                    newData += string.substring(stringStartIndex,matchEnd);
                    stringStartIndex = matchEnd;
                }

                //console.log("match start at " + match.index + " end at " + (match.index + match[0].length));
                index++;
            
            }//end of loop

            newData += string.substring(stringStartIndex,stringEndIndex);//works prefectly

            //when delete happens 3 thing must change
            //first text_data :
            $('#text_data').val(newData);
            //second remove span json
            deleteBtn.parent().parent().parent().remove();
            //refresh span jsons:
            jsonSpanArraySubmitBtnHandler(false, null);
            //console.log("new Data = " + newData);


        }
    })

}

function reGenerateSpansHtmlByJson() {

    const jsonString = $('.paragraph_spans_text_area').val().trim();
    let jsonArray;

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

    $(".paragraph_spans_handler").find(".showbox").find("#spans_sortable_list").empty();

    //console.log('jsonArray.length : ' + jsonArray.length);

    //print text of spans to graphical spans list:
    let regex = new RegExp('\\[span\\]\\[\\[\\*([\\s\\S]+?)\\*\\]\\]', 'g'); //g for global search
    let data = $("#text_data").val();
    let match = data.match(regex);
    let text_of_spans = [];
    if (match) {
        match.forEach(element => {
            let toPush = element.replace("\[span\]\[\[\*", '');
            toPush = toPush.replace("\*\]\]", '');
            //console.log('toPush : ' +toPush);
            text_of_spans.push(toPush);
        });
    }

    if (jsonArray == null) jsonArray = [];

    if (jsonArray.length > 0) {
        let index = 0;
        $.each(jsonArray, function (key, value) {
            //console.log("vs: " + value);
            const htmlrow = jsonSpanRowHtmlMacker(value, text_of_spans[index], index);
            $(".paragraph_spans_handler").find(".showbox").find("#spans_sortable_list").append(htmlrow);
            index++;
        });
    }

    $('.json_handler_box_opener_btn').click(jsonHandlersBoxOpener);
    $('.delete_span').click(deleteSpanFunction);
    $('.json_span_submit_array').off("click");
    //https://stackoverflow.com/a/9467172/4565796
    $('.json_span_submit_array').click({
        IsSingleItemEdit: true
    }, jsonSpanArraySubmitBtn);
    $('.json_span_cancel').click(jsonSpanCancelBtn);
    $('.color_selector_box > .color_box').click(pickerFunction);
    $('.mppanel_color_forms').on("change keyup paste", colorChangeListener);
    $('.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));});
    $('.clickable_select').on('change', ClickableSelectChanged);

}

function updatePreview() {

    let regex = new RegExp('\\[span\\]\\[\\[\\*([\\s\\S]+?)\\*\\]\\]', 'g'); //g for global search
    let data = $("#text_data").val();
    let spansJsonString = $(".paragraph_spans_text_area").text();
    if (spansJsonString.trim() == "") {
        spansJsonString = '[]';
    }
    let spans = JSON.parse(spansJsonString);
    let count = ((data || '').match(regex) || []).length;

    //build html for preview
    for (let i = 0; i < count; i++) {
        data = data.replace("\[span\]\[\[\*", '<span style="preview_style_part_' + i + '">');
        data = data.replace("\*\]\]", '</span>');
    }

    if (spans == null) spans = [];

    //build css for html preview
    for (let i = 0; i < spans.length; i++) {

        let underline = "none";
        if (spans[i]['underline'] == 1) underline = "underline";

        let weight = "400";
        if (spans[i]['bold'] == 1) weight = "600";

        let size = "15px";
        if (spans[i]['size'] == 1) size = "18px";

        let css_style = 'color:' + spans[i]['color'] + ';text-decoration:' + underline + ';font-weight:' + weight + ';font-size:' + size;

        data = data.replace("preview_style_part_" + i, css_style);

    }

    data = '<span style="color:' + $('#color').val() + '">' + data + '</span>';
    data = data.replace(/\n/g, "<br/>");
    
    $('.paragraph_text_area_preview').html(data);

}


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

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

    if ($(".paragraph_text_area_editor")[0]) {
        updatePreview();
    }

    if ($(".paragraph_spans_handler")[0]) { //there is json span list so generate it
        reGenerateSpansHtmlByJson();
    }

    $('#switch_to_editor').click(function () {
        $('#switch_to_editor').removeClass('btn-default');
        $('#switch_to_editor').addClass('btn-primary');
        $('#switch_to_preview').addClass('btn-default');
        $('#switch_to_preview').removeClass('btn-primary');
        $('#select_span').show();
        $('.paragraph_text_area_preview').hide();
        $('.paragraph_text_area_editor').show();
    });

    $('#switch_to_preview').click(function () {
        $('#switch_to_editor').addClass('btn-default');
        $('#switch_to_editor').removeClass('btn-primary');
        $('#switch_to_preview').removeClass('btn-default');
        $('#switch_to_preview').addClass('btn-primary');
        $('.paragraph_text_area_preview').show();
        $('.paragraph_text_area_editor').hide();
        $('#select_span').hide();
    });

    //add span codes:

    $(".paragraph_text_area_editor").on('click keyup', function (e) {

        element = $("#text_data")[0];
        selectIndex = element.selectionStart;
        selectedWord = window.getSelection().toString();
        selectionStartIndex = selectIndex;
        selectionEndIndex = selectIndex + selectedWord.length;
        //console.log("selectionStartIndex : "+selectionStartIndex + " | selectionEndIndex:" + selectionEndIndex)

    });

    $(".paragraph_text_area_editor").blur(function () {

        setTimeout(function () {
            //console.log('clear data')
            selectionStartIndex = null;
            selectionEndIndex = null;
        }, 1000);


    });

    $('#select_span').click(function () {
        if (selectionStartIndex == null) {
            notyf.error("لطفا ابتدا بخشی از متن را انتخاب کنید");
        } else {
            if (selectionStartIndex >= selectionEndIndex) {
                notyf.error("لطفا ابتدا حداقل یک کلمه را در ویرایشگر با کمک موس انتخاب کنید");
            } else {

                //add span:
                let string = $("#text_data").val();

                //console.log("string: " + string);

                let tempStringToCount = string.substring(0, selectionStartIndex);
                //console.log('tempStringToCount= ' +tempStringToCount);
                //console.log("1 string: " + string);
                let output = string.substring(0, selectionStartIndex) + '[span][[*' + string.substring(selectionStartIndex, selectionEndIndex) + '*]]' + string.substring(selectionEndIndex);
                //console.log("output: " + output);
                $("#text_data").val("");
                $("#text_data").val(output);

                let obj = {
                    "color": "",
                    "bold": "0",
                    "underline": "0",
                    "size": "0",
                    "intent_type": "0",
                    "intent_data": ""
                }

                let regex = new RegExp('\\[span\\]\\[\\[\\*([\\s\\S]+?)\\*\\]\\]', 'g');
                let spansJsonString = $(".paragraph_spans_text_area").text();
                if (spansJsonString.trim() == "") {
                    spansJsonString = '[]';
                }
                let spans = JSON.parse(spansJsonString);
                let count = ((tempStringToCount || '').match(regex) || []).length;
                //https://stackoverflow.com/a/586189/4565796
                spans.splice(count, 0, obj);

                $(".paragraph_spans_text_area").text(JSON.stringify(spans, null, 2));

                reGenerateSpansHtmlByJson();

                //finished:
                notyf.open({
                    type: 'info',
                    message: 'اسپن با موفقیت اضافه شد'
                });

            }
        }
    });

    $('.delete_span').click(deleteSpanFunction);

    $('#color').on('change', function (e) {
        //if color of paragraph changed update preview
        updatePreview();
    });
    
    
}); //end of jqury doc ready
