const errorModal = $( '#errorModal' );
const askQuestionModal = $( '#askQuestionModal' );
const readMoreModal = $( '#readMoreModal' );
const answerModal = $( '#answerModal' );
const welcomeModal = $('#welcomeModal' );
const welcomeModalText = $('#welcomeModalText');
const welcomeModalClose = $('#welcomeModalClose' );
const answerText = $('#answer' );
const answerModalTitle = $('#answerModalLabel');
readMoreModalText = $('#readMoreModalText' );
const readMoreModalTitle = $('#readMoreModalLabel' );
const errorMsg = $( '#errorMsg' );
const askErrorMsg = $('#askErrorMsg')
const answerErrorMsg = $('#answerErrorMsg' );
const questions = $( '#questions' )
const question = $('#question' );
const askButton = $('#askBtn' );
const nickname = $('#nickname' );
let is_owner = false;

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 ( !nickname.val() )
    {
        askErrorMsg.html( 'Please enter a name first!' );
        askButton.prop( 'disabled', false );
        return;
    }

    if( nickname.val().length > 20 || nickname.val().length < 3 )
    {
        askErrorMsg.html( 'The name should be 3-20 characters long.' );
        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(),"nickname":nickname.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>The nickname should contain at least 3 up to 20 characters!" );
                    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 ' + 'XXX' + " question" );
    answerErrorMsg.html( '' );

    if( !is_owner )
    {
        errorModal.modal( 'show' );
        errorMsg.html( 'You are not allowed to answer questions!<br>Ask the room-owner for permissions.' );
        return;
    }

    answerModal.modal( 'show' );

    request( 'getQuestion', {"question_id":id}, function( result )
    {
        answerModalTitle.html( 'Answer ' + result.data.created_by + "'s question" );
        if( result.data.answer !== null && result.data.answer.length > 5 )
        {
            let this_answer = result.data.answer;
            this_answer = new DOMParser().parseFromString(this_answer, "text/html").documentElement.textContent;

            this_answer.replace(/(?:\r\n|\r|\n)/g, '<br>');
            answerText.val( this_answer  );
        }
        else
        {
            answerText.val( '' );
        }
        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 > 1000 )
    {
        answerErrorMsg.html( 'The answer should contain 10-1000 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 text-warning">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="javascript:void(0);" onclick="openReadMoreModal(\''+ result.data.questions[i].id + '\');" class="card-link">Read more</a>' +
                    '        <a href="javascript:void(0);" onclick="openAnswerModal(\'' + result.data.questions[i].id + '\');" class="card-link">Answer</a>' +
                    '    </div>' +
                    '   </div>' +
                    '</div> ' )
            }
            let _sel = $('#qa_' + result.data.questions[i].id );

            if ( _sel.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>' );
                $('#q_' + result.data.questions[i].id + ' h5').addClass( 'text-info' ).removeClass( 'text-warning' );
            }
            else if ( result.data.questions[i].answer !== _sel.html() && 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 )
    {

    }
    );
}

function welcomeMessage()
{
    // Starting welcome modal
    welcomeModal.modal( 'show' );
    welcomeModalClose.prop( 'disabled', true );
    request( 'getWelcomeInfo', {}, function( result ) {
        if ( result.data.is_owner === true )
        {
            welcomeModalText.html( 'You are the owner of this room.<br>This means you are allowed to ask and <strong>answer</strong> questions!<br><br>To share your room code, use the share-url or the room-code.' );
            is_owner = true;
        }
        else
        {
            welcomeModalText.html( 'You are an guest of this room.<br>This means you are allowed to ask questions.<br>To ask a question, click on "Ask a question", then enter your name and your question.' );
            is_owner = false;
        }
        setTimeout( function() { welcomeModalClose.prop( 'disabled', false ); }, 500 );
    }, function()
    {
        is_owner = false;
        setTimeout( function() {
            welcomeModal.modal('hide');
        }, 500 );
        setTimeout( function(){
            errorMsg.html( "Oopsie! Your user information cannot be loaded.<br>Try reloading the page!" );

            errorModal.modal( 'show' );

        }, 800 );
    });

}

function closeWelcome() {
    let refresh_rate = $('#refresh_rate').val();
    if (refresh_rate < 2 || refresh_rate > 122) {
        refresh_rate = 2;
    }
    let q_interval = setInterval(function () {
        getQuestions();
    }, refresh_rate * 1000);

}

function copyShareUrl( btn )
{

    let share_url = document.getElementById( "share_url" );
    share_url.select();
    share_url.setSelectionRange(0, 99999) ;
    document.execCommand( "copy" );
    $(btn).html( 'Copied!' );
    setTimeout( function() { $(btn).html( 'Copy-URL' );}, 1500 );

}




setTimeout( function() { welcomeMessage(); }, 500 );