// This file contains all the logic to dynamically submit forms and handle other actions on the website
// We use Javascript with the help of Jquery and AJAX

// Submit signup form
$("form[name=signup_form").submit(function(e) {
    var $form = $(this);
    var $error = $form.find(".error")
    var data = $form.serialize();

    $.ajax({
        url: "/user/signup_verify",
        type: "POST",
        data: data,
        dataType: "json",
        success: function(resp) {
            window.location.href = "/";
        },
        error: function(resp) {
            console.log($error.text());
            $error.removeClass("error--hidden")
        }
    })
    e.preventDefault();
});

// Submit login form
$("form[name=login_form").submit(function(e) {
    var $form = $(this);
    var $error = $form.find(".error")
    var data = $form.serialize();

    $.ajax({
        url: "/user/login_verify",
        type: "POST",
        data: data,
        dataType: "json",
        success: function(resp) {
            window.location.href = "/";
        },
        error: function(resp) {
            console.log($error.text());
            $error.removeClass("error--hidden")
        }
    })
    e.preventDefault();
});

// Submit create class form
$("form[name=createclass_form").submit(function(e) {
    var $form = $(this);
    var $error = $form.find(".error")
    var data = $form.serialize();

    $.ajax({
        url: "/classes/create",
        type: "POST",
        data: data,
        dataType: "json",
        success: function(resp) {
            window.location.href = "/dashboard";
        },
        error: function(resp) {
            console.log($error.text());
            $error.removeClass("error--hidden")
        }
    })
    e.preventDefault();
});

// Submit joinclass form
$("form[name=joinclass_form").submit(function(e) {
    var $form = $(this);
    var $error = $form.find(".error")    
    var data = $form.serialize();

    $.ajax({
        url: "/classes/join",
        type: "POST",
        data: data,
        dataType: "json",
        success: function(resp) {
            window.location.href = "/dashboard";
        },
        error: function(resp) {
            console.log($error.text());
            $error.removeClass("error--hidden")
        }
    })
    e.preventDefault();
});

// Submit edit class form
$("form[name=edit_class").submit(function(e) {
    var $form = $(this);
    var $error = $form.find(".error");
    var $ids = $form.parent().parent().find('.updateClass');
    var data = $form.serialize();
    var new_data = data.concat("&","class_id=",$ids.attr('id'))

    $.ajax({
        url: "/classes/update",
        type: "POST",
        data: new_data,
        dataType: "json",
        success: function(resp) {
            window.location.href = "/dashboard";
        },
        error: function(resp) {
            console.log($error.text());
            $error.removeClass("error--hidden")
        }
    })
    e.preventDefault();
});

// prevent mbytes answers to submit by pressing enter
$("form[name=mbytesAnswers]").submit(function(e) {
    e.preventDefault();
});

// load morning bytes when clicking the button with class .loadBytes
$(".loadBytes").click(function(e) {
    var $btn = $(this);
    var $error = $btn.find(".error");
    var $to_replace = $btn.parent().parent();
    console.log($to_replace);
    $to_replace.html('<div class="container"> Loading your Question </div>');
    var $footer = $to_replace.parent().find('.modal-footer');
    $footer.removeAttr('hidden');
    var class_id = $footer.find('.submitBytes').attr('byteid');
    console.log('class_id='+ class_id);
    $to_replace.parent().find('.btn-close').remove();
    

    $.ajax({
        url: "/qb/get_questions",
        type: "GET",
        data: {'class_id': class_id},
        dataType: "json",
        success: function(resp) {
            console.log(resp)
            let replacement = `<div class="card-header text-center"><strong>Question</strong></div>
            <form name="mbytesAnswers"><div class="card mb-3">
            <div class="card-body">
            <strong>${resp['question']}</strong><br><br>`
            // let replacement = '<form name="mbytesAnswers"><div class="card mb-3">';
            // replacement = replacement + '<div class="card-body">';
            // replacement = replacement + resp['question'] + '<br><br>';
            if (resp['type']=='multiple'){
                for(let x in resp['option']){
                    replacement = replacement + `<div class="form-check">
                    <input class="form-check-input" type="radio" name="answer" id="question" value="${ resp['option'][x]}">
                    <label class="form-check-label" for="question"> ${resp['option'][x]}</label></div>`
                    // replacement = replacement + '<div class="form-check">'
                    // replacement = replacement + '<input class="form-check-input" type="radio" name="answer'+
                    // '" id="question" value="' + resp['option'][x] +'">'+
                    // '<label class="form-check-label" for="question">' +resp['option'][x]+'</label></div>'
                }
            } else {
                replacement = replacement + '<input type="text" class="form-control" id="answer" name="answer" placeholder="Your Answer" />'
            }
            replacement = replacement + `</div>
            </div>
            <button type="submit" disabled hidden=true aria-hidden=true>
            </form>`
            $to_replace.html(replacement);

        },
        error: function(resp) {
            console.log($error.text());
            $error.removeClass("error--hidden")
        }
    })
    e.preventDefault();
});

// submit morning bytes when clicking the button with class .submitBytes
$(".submitBytes").click(function(e) {
    var $btn = $(this);
    var $error = $btn.find(".error");
    var $form = $btn.parent().parent().find('form[name=mbytesAnswers]');
    var data = $form.serialize();
    console.log(data)

    if(data.length > 8){
        $.ajax({
            url: "/assignment/submit",
            type: "POST",
            data: data,
            dataType: "json",
            success: function(resp) {
                console.log('im here')
                console.log(resp)
                var $dad = $form.parent()
                $dad.html(`<div class="card mb-3 reviewBytes">
                <div class="card-header text-center"><strong>Review and Feedback</strong></div>
                <div class="card-body"> <p>${resp['feedback']}<br></p>
                <p> Read more <a href=${resp['resource']}> here </a></p>
                </div>
                <a href="/dashboard" class="btn btn-outline-success reload">
                Back to Dashboard!
                </a>
            </div>`)
                $dad.parent().find('.submitBytes').remove()
            },
            error: function(resp) {
                console.log($error.text());
                $error.removeClass("error--hidden")
            }
        })
    }else{
        console.log('empty')
    }
    e.preventDefault();
});

//button to reload page
$(".reload").click(function(e) {
    location.reload();
});

//reset profesor update form when dismissing the modal
$('.professor_modal').on('hidden.bs.modal', function () {
    $(this).find('form').trigger('reset');
})

//remove a class on a professor dashboard
$(".removeClass").click(function(e) {
    var $btn = $(this);
    var $error = $btn.find(".error");
    var class_id = $btn.attr("class_id")
    class_id = 'class_id='+ class_id
    console.log(class_id)
    $.ajax({
        url: "/classes/delete",
        type: "DELETE",
        data: class_id,
        dataType: "json",
        success: function(resp) {
            window.location.href = "/dashboard";
        },
        error: function(resp) {
            console.log($error.text());
            $error.removeClass("error--hidden")
        }
    })
    e.preventDefault();
});

//change topics for a class on a professor dashboard
$(".topics").change(function(e) {
    var $selector = $(this);
    var class_id = 'class_id=' + $selector.attr('class_id');
    var new_topic = '&new_topic='+ $selector.val();
    var data = class_id + new_topic;
    
    $.ajax({
        url: "/classes/update_topic",
        type: "PUT",
        data: data,
        dataType: "json",
        success: function(resp) {
            window.location.href = "/dashboard";
        },
        error: function(resp) {
            console.log($error.text());
            $error.removeClass("error--hidden")
        }
    })
    e.preventDefault();
});
