//variables admins, canUserComment and currentUser are initialized in dashboard and landing twig files.
admins = Object.keys(admins).map((key) => admins[key]);

let replyCounter = 0;


function getCommentFormString(commentId) {
    return `
    <form name="form" data-id="${commentId}" method="post" class="comment-form">
        <div class="form-group">
            <label class="" for="reply_form_firstName_${commentId}">نام</label>
            <input type="text" id="reply_form_firstName_${commentId}" name="form[firstName]" placeholder="" class="form-control" required ${currentUser ? `value=${currentUser.firstName} disabled` : ''} />
        </div>
        <div class="form-group">
            <label class="" for="reply_form_lastName_${commentId}">نام خانوادگی</label>
            <input type="text" id="reply_form_lastName_${commentId}" name="form[lastName]" placeholder="" class="form-control" required ${currentUser ? `value=${currentUser.lastName} disabled` : ''}/>
        </div>
    
        ${!currentUser ? `
        <div class="form-group">
            <label class="" for="reply_form_phoneemail_${commentId}">تلفن همراه یا ایمیل (اختیاری)</label>
            <input type="text" id="reply_form_phoneemail_${commentId}" name="form[phoneemail]" class="ltr form-control" placeholder="" />
        </div>` : ''}
    
        <div class="form-group">
            <label class="required" for="reply_form_comment_${commentId}">نظر شما</label>
            <textarea id="reply_form_comment_${commentId}" name="form[comment]" required="required" style="min-height: 100px;" placeholder="نظر خود را وارد کنید..." class="form-control" autofocus></textarea>
        </div>
        <button type="submit" id="reply-submit-btn-${commentId}" class="btn btn-block btn-danger">ارسال</button>
        <input type="hidden" id="form__token" name="form[_token]" value="1jG8ozmiInIPYoylUoOPNMkrNxwsWYm1UCryG4vPrTs" />
    </form>
    `
}

function getComments(comments, result, isReply = false) {
    console.log(comments);
    if (isReply) {
        result += '<ul class="pr-4 my-1" style="list-style: none; width: 100%;">';
    }

    comments.forEach(function (comment, index) {
        result += getComment(comment, comments.length - 1 === index);
    })

    if (isReply) {
        result += '</ul>';
    }

    return result;
}

function getComment(data, isLastComment) {
    let comment = data.comment;
    let replies = data.replies;
    let hasReply = data.hasReply;
    let isReply = data.comment.isReply;

    let result = '';
    if (isReply) {
        result = `
                <li style="${comment.status !== 1 ? 'background-color: #f3f3f3' : ''}" id="comment_${comment.id}" class="position-relative">
                    <div style="position:absolute; height: ${isLastComment ? 'calc(20px + 0.25rem);' : 'calc(100% + 0.25rem);'} width: 1px; right: -0.75rem; top: -0.25rem; background-color: #ddd"></div>
                    <div style="position:absolute; height: 1px; width: 0.75rem; right: -0.75rem; top: 20px; background-color: #ddd"></div>
                        <div class="px-2" style="border: 1px solid #eee; ${comment.status === 1 && admins.includes(comment.userId) ? 'background-color: #fff0f0;' : ''}">`;
    } else {
        result = '<div class="col-sm-12 more-comments px-2" ' + (comment.status !== 1 ? 'style="background-color: #f3f3f3"' : '') + 'id="comment_' + comment.id + '">';
    }
    result += `
                        <div class="d-flex justify-content-between">
                            <div class="d-flex align-items-end">
                            <span class="font-weight-bold ml-2" style="font-size: 0.9rem">
                                ${comment.username}
                            </span>
                            ${comment.vote ? `
                            <span class="ltr d-inline-block ml-2" style="margin-bottom: -5px;">
                                <input id="input-id" name="input-name" type="number" class="rating" min="1" max="5" step="0.1" data-readonly="true" data-hover-enabled="false" data-show-caption="false" data-show-clear="false" data-size="xs" data-language="fa" value="${comment.vote}">
                            </span>
                            ` : ''}
                            <span class="text-muted" style="font-size: 0.7rem">
                                ${comment.date}
                            </span>
                            </div>
                        <div id="reply_icon_${comment.id}">
                            ${comment.status === 1 && canUserComment ? '<a class="comment-reply-icon mr-2" href="javascript:void(0)" data-toggle="collapse" data-target="#reply_form_' + comment.id + '" aria-expanded="true" aria-controls="reply_form_' + comment.id + '"><i class="fas fa-reply fa-flip-horizontal" data-toggle="tooltip" title="پاسخ"></i></a>' : ''}
                        </div>
                        </div>
                        <div>
                            <p style="font-weight: 300; white-space: pre-line; word-wrap: break-word">${comment.comment}</p>
                        </div>

                        <div id="reply_form_${comment.id}" class="reply-form-collapse collapse" aria-labelledby="heading-${comment.id}" style="flex: 1">
                            ${comment.status === 1 && canUserComment ? `
                            <div class="p-3" style="background-color: #f9f9f9">
                                ${getCommentFormString(comment.id)}
                            </div>
                            ` : ''}
                        </div>

                        ${hasReply ? '<div class="d-flex justify-content-end">' +
        '   <a class="float-left load-more-replies" href="#" data-id="' + comment.id + '  " style="font-size: 0.7rem" >ادامه پاسخ‌ها...</a>' +
        '</div>' : ''}

                        <div id="comment_links_${comment.id}"
                             style="display: flex; justify-content: flex-end;">
                        ${comment.status !== 1 ? '<a class="float-left" href="javascript:void(0)" onclick="publishComment('+comment.id+')" ><span class="badge badge-success "> <i class="fa fa-check"></i> انتشار </span></a>' : ''}
                        </div>`;

    if (isReply) {
        result += '</div>';
        if (replies.length > 0) {
            result += getComments(replies, '', true);
        }
        result += '</li>';
    } else {
        if (replies.length > 0) {
            result += getComments(replies, '', true);
        }
        result += '</div><div class="col-sm-12 p-0"><hr class="my-1"></div>';
    }
    return result;
}


var site_timeout_default = 10;
var site_timeout = site_timeout_default;
var max_timeout = 30;

var page  = 2;

function loadMoreComments(thisObj, payload) {
    thisObj.html('<i class="fa fa-spinner fa-spin fa-2x"></i>');
    $.ajax({
        url: payload.url,
        type: 'POST',
        dataType: 'json',
        timeout: (site_timeout * 1000),
        async: true,
        cache: false,
        data: {
            page: page,
            is_teacher: payload.is_teacher,
        },
        success: function (data) {
            isEmpty = data.isEmpty;
            if(isEmpty){
                $("#morecomments").remove();
            }else{
                $("#morecomments").html('مشاهده بیشتر');
            }
            comments = data.comments;
            page++;
            let positionX = window.scrollX;
            let positionY = window.scrollY;
            $("#commnets-row").append(getComments(comments, ''));
            $(".new-comment").fadeIn(1000);
            window.scrollTo(positionX,positionY);
            $(".rating").rating();
            // $.each(comments,function (i,comment) {

            // let firstname = (comment.firstName)?comment.firstName:'';
            // let lastname = (comment.lastName)?comment.lastName:'';
            // let vote = '';
            // if(comment.vote){
            //     vote =  '<span class="ltr d-inline-block">\n' +
            //         '  <input id="comment-star-'+comment.id+'" name="input-name" type="number" class="rating" min="1" max="5" step="0.1" data-readonly="true" data-hover-enabled="false" data-show-caption="false" data-show-clear="false" data-size="xs" data-language="fa" value="'+ comment.vote +'">\n' +
            //         '</span><br>\n';
            // }
            // $("#commnets-row").append('<div class="col-sm-12 new-comment p-2" id="comment_'+comment.id+'" ' +
            //     (comment.status != 1 ? 'style="display: none; background-color:#f3f3f3"' : 'style="display: none"') +
            //     '>' +
            //     '                             <div class="col-sm-4">\n' +
            //     '                                <div class="row">\n' +
            //     '                                    <div class="col-sm-4">\n' +
            //     '                                        <div class="comment-avatar">\n' +
            //     '                                                <span class="font-weight-bold">' + (comment.firstName).slice(0, 1) + '</span>\n' +
            //     '                                        </div>\n' +
            //     '                                    </div>\n' +
            //     '                                   <div class="col-sm-8 ">\n' +
            //     '                                        <p class="mb-0 pb-0" style="font-size: 12px; color: #6f6f6f">' + comment.createdDate +
            //     '                                        <h5 class="font-weight-bold ">' + firstname + ' ' + lastname +
            //     '                                        </h5>\n' +
            //     '                                    </div>\n' +
            //     '                                </div>\n' +
            //     '                            </div>\n' +
            //     '                            <div class="col-sm-8" style="font-size: 13px;">\n' +
            //     vote +
            //     comment.comment +
            //     (comment.status != 1 ? '' +
            //         '<div class="dropdown show float-left" id="comment_links_'+comment.id+'">'+
            //             '<a href="javascript:void(0)" onclick="publishComment('+comment.id+')" ><span class="badge badge-success "> <i class="fa fa-check"></i> انتشار </span></a>'+
            //         '</div>' : '') +
            //     '                            </div>\n' +
            //     '</div>' +
            //     '                            <div class="col-sm-12">\n' +
            //     '                                <hr>\n' +
            //     '                            </div>'
            // );
            // $(".new-comment").fadeIn(1000);
            // window.scrollTo(positionX,positionY);
            // $(".rating").rating();

            // });
        },
    });
    return false;
}

function publishCommentAjax(payload)
{
    var comment_id = payload.commentId;

    var param = {
    };


    $.ajax({
        //url: '/app_dev.php'+ajaxURL,
        url: payload.url,
        type: "POST",
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        dataType: "json",
        data: param,
        cache: false,
        timeout: (site_timeout * 1000),
        async: true,
        enctype: 'multipart/form-data',
        success: function (recivedData) {
            $(`#comment_`+comment_id).removeAttr('style');
            $(`#comment_links_`+comment_id).html('<span style="color: green; font-size: 0.8em;"> منتشر شد</span>');
            if (canUserComment) {
                $('#reply_icon_' + comment_id).html('<a class="comment-reply-icon mr-2" href="javascript:void(0)" data-toggle="collapse" data-target="#reply_form_'+comment_id+'" aria-expanded="true" aria-controls="reply_form_'+comment_id+'"><i class="fas fa-reply fa-flip-horizontal" data-toggle="tooltip" title="پاسخ"></i></a>');
                $('#reply_form_' + comment_id).html(`
                <div class="p-3" style="background-color: #f9f9f9">
                    ${getCommentFormString(comment_id)}
                </div>
                `);

            }
            setTimeout(function() {
                $(`#comment_links_`+comment_id).fadeOut('slow');
            }, 2000);
        },
        error: function (data) {
            var data  = data.responseJSON;
            toastr.options.positionClass = 'toast-bottom-left';
            toastr.error(data.message);
        }
    });

};

function handleCommentFormSubmit(thisObj, commentId, url) {

    var data, commentBodyElement, commentBody, firstName, lastName, phoneemailElement = null;
    if (!commentId) { //it's a reply
        commentBodyElement = $('#comment_form_comment');
        commentBody = commentBodyElement.val();
        firstName = $('#comment_form_firstName').val();
        lastName = $('#comment_form_lastName').val();
        phoneemailElement = $('#comment_form_phoneemail');
    } else { //it's a regular comemnt
        commentBodyElement = $('#reply_form_comment_' + commentId);
        commentBody = commentBodyElement.val();
        firstName = $('#reply_form_firstName_' + commentId).val();
        lastName = $('#reply_form_lastName_' + commentId).val();
        phoneemailElement = $('#reply_form_phoneemail_' + commentId);
    }
    data = {
        firstName,
        lastName,
        commentBody,
        phoneemail: phoneemailElement ? phoneemailElement.val() : null,
    };

    if (commentBody.length === 0) {
        toastr.options.positionClass = 'toast-bottom-left';
        toastr.warning('متن پیام نمی‌تواند خالی باشد!');
        return false;
    }

    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        timeout: (site_timeout * 1000),
        async: true,
        cache: false,
        data: data,
        beforeSend: function () {
            if (commentId) {
                $('#reply-submit-btn-' + commentId).html('<i class="fa fa-spinner fa-spin"></i>');
            } else {
                $('#comment_submit_btn').html('<i class="fa fa-spinner fa-spin"></i>');
            }
        },
        success: function (data) {
            if (commentId) {
                $('#reply-submit-btn-' + commentId).html('ارسال');
                $('#reply_form_' + commentId).collapse('hide');
            } else {
                $('#comment_submit_btn').html('ارسال');
                $('#comment_form').collapse('hide');
            }
            commentBodyElement.val('');
            replyCounter++;
            thisObj.parent().parent().before(`
                <div class="alert alert-success mb-1" id="comment_send_success_${replyCounter}" style="display: none">
                    ${data.message}
                </div>
            `);
            thisObj.parent().parent().before(`
                <div class="card mb-1" id="comment_send_card_${replyCounter}" style="transition: border-color 0.3s ease; border-color: var(--primary-border-color); display: none">
                    <div class="card-header">
                        <i class="fas fa-user"></i>
                        ${firstName} ${lastName} ${currentUser ? '' : '(مهمان)' }
                    </div>
                    <div class="card-body" style="white-space: pre-line; word-wrap: break-word">${commentBody.trim()}</div>
                </div>
            `)
            $('#comment_send_success_' + replyCounter).fadeIn('slow');
            $("#comment_send_card_" + replyCounter).fadeIn('slow', function () {
                $([document.documentElement, document.body]).animate({
                    scrollTop: $("#comment_send_card_" + replyCounter).offset().top - $(window).height() / 2
                }, 300);
            });
            let counter = replyCounter;
            setTimeout(function () {
                $('#comment_send_success_' + counter).fadeOut('slow', function () {
                    $(this).remove();
                    $("#comment_send_card_" + counter).css('border-color', 'rgba(0,0,0,.125)');
                });
            }, 5000);
        },
        error: function (response) {
            if (commentId) {
                $('#reply-submit-btn-' + commentId).html('ارسال');
            } else {
                $('#comment_submit_btn').html('ارسال');
            }
            toastr.options.positionClass = 'toast-bottom-left';
            toastr.error(response.responseJSON ? response.responseJSON : 'خطایی در ارسال کامنت رخ داد!');
        }
    })
}

function loadMoreReplies(thisObj, payload) {
    thisObj.html('<i class="fa fa-spinner fa-spin"></i>');
    var target = thisObj;
    var targetParent = thisObj.parent().parent().parent();
    $.ajax({
        url: payload.url,
        type: 'GET',
        timeout: (site_timeout * 1000),
        async: true,
        cache: false,
        success: function (data) {
            var reply = getComments(data, '', true);
            targetParent.append(reply);
            target.fadeOut('fast');
        },
        error: function (response) {
            target.html('مشاهده پاسخ‌ها...');
        }
    });
    return false;
}

$(`#comment_title`).on('mouseenter',function (){
    $(`#comment_list_link`).show()
});
$(`#comment_title`).on('mouseleave',function (){
    $(`#comment_list_link`).hide()
});
$(document).on( 'shown.bs.collapse', '.comment-form-collapse', function () {
    if (currentUser) {
        $('#comment_form_comment').focus();
    } else {
        $('#comment_form_firstName').focus();
    }
    $('.reply-form-collapse.show').add('.comment-form-collapse.show').not(this).collapse('hide');
})
$(document).on('shown.bs.collapse', '.reply-form-collapse', function () {
    let id = $(this).attr('id');
    //convert reply_form_1234 to 1234
    id = id.replace('reply_form_', '');
    if (currentUser) {
        $('#reply_form_comment_' + id).focus();
    } else {
        $('#reply_form_firstName_' + id).focus();
    }
    $('.reply-form-collapse.show').add('.comment-form-collapse.show').not(this).collapse('hide');
})