errorModal = $( '#errorModal' );
askQuestionModal = $( '#askQuestionModal' );
readMoreModal = $( '#readMoreModal' );
answerModal = $( '#answerModal' );
answerText = $('#answer' );
answerModalTitle = $('#answerModalLabel');
readMoreModalText = $('#readMoreModalText' );
readMoreModalTitle = $('#readMoreModalLabel' );
errorMsg = $( '#errorMsg' );
askErrorMsg = $('#askErrorMsg')
answerErrorMsg = $('#answerErrorMsg' );
questions = $( '#questions' )
question = $('#question' );
askButton = $('#askBtn' );

function request( a_uri, a_data, a_successhandler, a_errorhandler )
{
    $.ajax(
        {
            url: "?c=Faq&a=" + a_uri,
            type: 'POST',
            data: JSON.stringify( a_data ),
            dataType: 'json',
            success: function (result)
            {
                a_successhandler(result);
            },
            error: function ( result, errorcode  )
            {
                if( errorcode === "parseerror" )
                {
                    $('.modal').modal( 'hide' );
                    setTimeout( function(){
                        $('.modal').modal('hide');

                        errorMsg.html( 'The action was not successfully.<br>Our server sent a weird response. Cannot parse this shit lmao' );

                        errorModal.modal( 'show' );
                        askButton.prop( 'disabled', false );
                    }, 500 );
                }
                a_errorhandler( result, errorcode );

            },
        });
}


function askQuestion()
{
    askButton.prop( 'disabled', true );
    if ( !question.val() )
    {
        askErrorMsg.html( 'Please enter a question first!' );
        askButton.prop( 'disabled', false );
        return;
    }

    if( question.val().length > 500 || question.val().length < 10 )
    {
        askErrorMsg.html( 'The question should be 15-50 characters long.' );
        askButton.prop( 'disabled', false );
        return;
    }

    request( 'addQuestion', {"question":question.val()},
        function( result ){
            askErrorMsg.html( '' );
            askButton.prop( 'disabled', false );
            question.val('');
            askQuestionModal.modal( 'hide' );
        }, function( result ) {
            askButton.prop( 'disabled', false );
            switch( result.status )
            {
                case 901:
                case 902:
                    askErrorMsg.html( "Something wrong happened. We don't know why...<br>Try again later please!" );
                    break;
                case 903:
                    askErrorMsg.html( "The question should contain at least 10 up to 500 characters!<br>Just not romans, but also not just 'help'." );
                    break;
                default:
                    $('.modal').modal('hide');
                    setTimeout( function( result ){
                        errorMsg.html( "The action was not successfully.<br>Maybe the room doesn't exist anymore.<br>Also may check your internet connection." );
                        errorModal.modal( 'show' );

                    }, 500 );
            }
        }
    );
}

function openReadMoreModal( id )
{
    readMoreModal.modal( 'show' );
    readMoreModalText.html( 'Loading...' );
    readMoreModalTitle.html( 'Question from: Anonymous' );
    request( 'getQuestion', {"question_id":id}, function( result )
    {
        let _answer = '';
        if( result.data.answer === null || result.data.answer.length < 5 )
        {
            _answer = 'So far there is no answer to this question.';
        }
        else
        {
            _answer = result.data.answer;
        }
        readMoreModalTitle.html( 'Question from: ' + result.data.created_by );
        readMoreModalText.html( '<strong>Question</strong><br>' + result.data.question +
                                '<hr><strong>Answer</strong><br>' + _answer
        );
    }, function() {
        readMoreModalText.html( 'An error occurred, please try again later!' );
    });

}

let answer_id = 0;
function openAnswerModal( id )
{
    answerModalTitle.html( 'Answer ' + 'Anonymous' + " question" );
    answerErrorMsg.html( '' );
    answerModal.modal( 'show' );

    request( 'getQuestion', {"question_id":id}, function( result )
    {
        readMoreModalTitle.html( 'Answer ' + result.data.created_by + " question" );
        if( result.data.answer !== null && result.data.answer.length > 5 )
        {
            answerText.val( result.data.answer );
        }
        answer_id = result.data.id;
    }, function() {
        answerErrorMsg.html( 'An error occurred, please try again!' );
    });
}

function answer()
{
    answerErrorMsg.html( '' );
    if( answer_id === 0 )
    {
        return;
    }

    if( answerText.val().length < 5 || answerText.val().length > 500 )
    {
        answerErrorMsg.html( 'The answer should contain 10-500 characters!' );
        return;
    }

    request( 'addAnswer', {"question_id":answer_id,"answer":answerText.val()}, function( result )
    {
        answerErrorMsg.html( '' );
        answerModal.modal( 'hide' );
    }, function( result ) {
        switch( result.status )
        {
            case 905:
                answerErrorMsg.html( 'You are not allowed to answer questions!' );
                break;
            default:
                answerErrorMsg.html( 'An error occurred. Please try again later!' );
        }

    });
}

function getQuestions()
{
    request( 'getQuestions', {}, function (result)
    {
        let questions_list = [];

        for (let i = 0; i < result.data.questions.length; i++)
        {
            questions_list.push( 'q_' + result.data.questions[i].id );
            if( $('#q_' + result.data.questions[i].id ).length < 1 )
            {
                questions.append( '<div class="col-sm-6 col-lg-4 col-md-5"><div class="card" id="q_' + result.data.questions[i].id + '" style=" margin-bottom: 10px;">' +
                    '    <div class="card-body">' +
                    '        <h5 class="card-title">Question</h5>' +
                    '        <h6 class="card-subtitle mb-2 text-muted">From ' + result.data.questions[i].created_by + '</h6>' +
                    '        <p class="card-text">'+ result.data.questions[i].question + '</p>' +
                    '        <a href="#" onclick="openReadMoreModal(\''+ result.data.questions[i].id + '\');" class="card-link">Read more</a>' +
                    '        <a href="#" onclick="openAnswerModal(\'' + result.data.questions[i].id + '\');" class="card-link">Answer</a>' +
                    '    </div>' +
                    '   </div>' +
                    '</div> ' )
            }
            else if ( $( '#qa_' + result.data.questions[i].id ).length < 1 && result.data.questions[i].answer !== null && result.data.questions[i].answer.length > 5 )
            {
                $('#q_' + result.data.questions[i].id + ' p' ).html( result.data.questions[i].question + '<hr><span id="qa_' + result.data.questions[i].id + '">' + result.data.questions[i].answer + '</span>' );
            }


        }

        /* FIX! $('#questions').children('div').forEach( function()
        {
            if( jQuery.inArray( this.id, questions_list ) === -1 )
            {
                $(this).remove();
            }
        } );*/

    },
    function ( result )
    {

    }
    );
}

getQuestions();
setInterval( function() { getQuestions(); }, 1500 );