{% extends "./template.html" %}
{% block content %}
<body onload="on_page_load()">
    <div class="card mt-4">
        <div class="card-header">
            <h2>Automatic Diagnostics</h2>
        </div>
        <div class="card-body">
            The following diagnostics will run automatically by the system.
            <table class="table table-hover">
                <tr>
                    <td width="30%">Diagnostic Test</td>
                    <td width="70%">Status</td>
                </tr>
                <tr id="test_email">
                    <td>Email Test</td>
                    <td>
                        Method<br/>
                        ~~~~~~<br/>
                        1.) NearBeach will send out an email to your email address<br/>
                        2.) If there is an error it will post it here<br/>
                        3.) If you receive the email - this functionality works<br/>
                    </td>
                </tr>
                <tr id="test_database">
                    <td>Database Issue</td>
                    <td>
                        Method<br/>
                        ~~~~~~<br/>
                        1.) NearBeach will select ALL users from the database<br/>
                        2.) If there is no error - this functionality works<br/>
                    </td>
                </tr>
                <tr id="test_location_services">
                    <td>Location Services</td>
                    <td>
                        Method<br/>
                        ~~~~~~<br/>
                        1.) NearBeach will find out if your location services work<br/>
                        2.) It will ping the following in the order of<br/>
                        a.) Mapbox<br/>
                        b.) Google Maps</br/
                        3.) If there are no errors - this functionality works<br/>
                    </td>
                </tr>

            </table>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header">
            <h2>Manual Diagnostics</h2>
        </div>
        <div class="card-body">
            The following tests will require you to follow the instructions.
            <table class="table table-hover">
                <tr>
                    <td width="30%">Diagnostic Test</td>
                    <td width="70%">Status</td>
                </tr>
                {% if RECAPTCHA_PUBLIC_KEY == "" %}
                    <tr id="test_recaptcha" style="background-color: red;">
                        <td>Recaptcha</td>
                        <td>RECAPTCHA_PUBLIC_KEY has not been filled out in the settings.py file</td>
                    </tr>
                {% else %}
                    <tr id="test_recaptcha">
                        <td>Recaptcha</td>
                        <td>
                            Method<br/>
                            ~~~~~~<br/>
                            1.) Fill out the reCaptcha<br/>
                            2.) Once you have a valid reCaptcha, click on the "Submit" button<br/>
                            Results will be displayed here
                            <form id="recaptcha_form" method="post">
                                {% csrf_token %}
                                <script src='https://www.google.com/recaptcha/api.js'></script>
                                <div class="g-recaptcha" data-sitekey="{{ RECAPTCHA_PUBLIC_KEY }}"></div>
                                <input type="submit" value="Check reCAPTCHA">
                            </form>
                        </td>
                    </tr>
                {% endif %}
                <tr id="weasy_print">
                    <td>Weasy Print<br/>Render PDF</td>
                    <td>
                        <div id="render_pdf">
                            <button class="btn btn-primary" onclick="download_pdf()">Click to download PDF</button>
                        </div>
                    </td>
                </tr>
                <tr id="test_document_upload">
                    <td>Document Uploading/Downloading</td>
                    <td>
                        <form id="document_upload">
                            Method<br/>
                            ~~~~~~<br/>
                            1.) Click on the "Browse..." button and select a document to upload<br/>
                            2.) Click on the "Upload" hyperlink<br/>
                            3.) Follow part 2 method<br/>
                            {% csrf_token %}<br/>
                            {{ diagnostic_test_document_upload_form.document }}<br/>

                        </form>
                    </td>
                </tr>
                <tr id="document_row_uploads">
                    <td colspan="2">
                        <div id="progress" style="border: none; width: 100%;">
                            <span id="upload_percent"><a href="javascript:void(0)" onclick="upload_document()">Upload Document</a></span>
                            <div id="upload_progress" style="background-color: green; width: 0%; height: 20px;"></div>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </div>
<script>
    $("#test_recaptcha").on("submit", function(e) {
        e.preventDefault();
        test_recaptcha();
    });

    function on_page_load() {
        /*
        When the page loads we want to run each diagnostic issue. Each diagnostic issue has it's own function.
        If there is an error with any funciton, it will display in the description box.
         */
        test_email();
        test_database();
        test_location_services();
    }

    function download_pdf() {
        //Download the PDF
        $.ajax({
            url: '/diagnostic_render_pdf/',
            data: {},
            dataType: 'HTML',
            type: 'GET',
            success: function(data) {
                /*
                Issue
                ~~~~~
                AJAX can not download a file - this is due to security issues. We have the AJAX here to pick up ANY
                issues with the rendering of the document. From here we just update the values and go to the PDF location.
                */
                var render_pdf = document.getElementById("render_pdf");
                render_pdf.innerHTML = `
                    <label>Did the PDF Download correctly?</label>
                    <div class="form-row">
                        <button class="btn btn-primary" onclick="download_pdf_yes()">Yes</button>
                        <button class="btn btn-warning" onclick="download_pdf_no()">No</button>
                    </div>
                `;

                //Now send the user the pdf
                location.href = '/diagnostic_render_pdf/';
            },
            error: function (jqXHR, exception) {
                /*
                Email failed. The reason will be written here.
                */
                var error_message = '';

                if (jqXHR.status === 0) {
                    error_message = 'No connection, please verify that you have a network connection.';
                } else if (jqXHR.status == 404) {
                    error_message = '404 returned - please check to make sure that the connection to the email server is existing';
                } else if (jqXHR.status == 500) {
                    error_message = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    error_message = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    error_message = 'Time out error.';
                } else if (exception === 'abort') {
                    error_message = 'Ajax request aborted.';
                } else {
                    error_message = 'There was a database error\n~~~~~~~~~~~' + jqXHR.responseText;
                }

                var render_pdf = document.getElementById("render_pdf");

                render_pdf.innerHTML = `
                    <div class="alert alert-warning">
                        Rendering PDF did not work. Please get your system administration to follow the instructions -
                        <a href="https://nearbeach.atlassian.net/wiki/spaces/HTIN/pages/239534081/Trouble+Shooting+-+Weasy+Print" target="_blank">Fix Weasy Print</a>
                    </div>
                    <div class="alert alert-warning">
                        ${error_message}
                    </div>
                `
            },
        });
    }

    function download_pdf_no() {
        $('#weasy_print td')[1].innerHTML = `<p>Test Failed. Please see instructions - <a href="" target="_blank"></a>`;
        $("#weasy_print").css("background-color", "red");

    }

    function download_pdf_yes() {
        $('#weasy_print td')[1].innerHTML = `<p>Test done successfully</p>`;
        $("#weasy_print").css("background-color", "lightgreen");

    }


    function test_email() {
        /*
        Method
        ~~~~~~
        1.) Calls the diagnostic URL
        2.) NearBeach will send an email to noreply@nearbeach.org
        3.) If there is an issue, it will display it here
        4.) If there is no issue, it will green the row and change the text to "Successful"
         */
        $("#test_email").css("background-color","lightblue");
        $("#test_email td")[1].append("Running Test...");


        $.ajax({
            url: '/diagnostic_test_email/',
            type: 'GET',
            datatype: 'HTML',
            data: {},
            success: function(data) {
                $("#test_email td")[1].innerHTML = "Test Successful";
                $("#test_email").css("background-color", "lightgreen");
            },
            error: function (jqXHR, exception) {
                /*
                Email failed. The reason will be written here.
                */
                var error_message = '';

                if (jqXHR.status === 0) {
                    error_message = 'No connection, please verify that you have a network connection.';
                } else if (jqXHR.status == 404) {
                    error_message = '404 returned - please check to make sure that the connection to the email server is existing';
                } else if (jqXHR.status == 500) {
                    error_message = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    error_message = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    error_message = 'Time out error.';
                } else if (exception === 'abort') {
                    error_message = 'Ajax request aborted.';
                } else {
                    error_message = `Email Error<br/>~~~~~~~~~~~<br/>${jqXHR.responseText}`;
                }
                $('#test_email td')[1].innerHTML = error_message;
                $("#test_email").css("background-color", "red");
                },
        });

    }

    function test_database() {
        /*
        Method
        ~~~~~~
        1.) Calls the diagnostic URL
        2.) NearBeach will pull data from the user table
        3.) If there is an issue, it will display it here
        4.) If there is no issue, it will green the row and change the text to "Successful"
         */
        $("#test_database").css("background-color","lightblue");
        $("#test_database td")[1].append("Running Test...");


        $.ajax({
            url: '/diagnostic_test_database/',
            type: 'GET',
            datatype: 'HTML',
            data: {},
            success: function(data) {
                $("#test_database td")[1].innerHTML = "Test Successful";
                $("#test_database").css("background-color", "lightgreen");
            },
            error: function (jqXHR, exception) {
                /*
                Email failed. The reason will be written here.
                */
                var error_message = '';

                if (jqXHR.status === 0) {
                    error_message = 'No connection, please verify that you have a network connection.';
                } else if (jqXHR.status == 404) {
                    error_message = '404 returned - please check to make sure that the connection to the email server is existing';
                } else if (jqXHR.status == 500) {
                    error_message = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    error_message = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    error_message = 'Time out error.';
                } else if (exception === 'abort') {
                    error_message = 'Ajax request aborted.';
                } else {
                    error_message = `There was a database error<br/>~~~~~~~~~~~<br/>${jqXHR.responseText}`;
                }
                $('#test_database td')[1].innerHTML = error_message;
                $("#test_database").css("background-color", "red");
            },
        });
    }

    function test_location_services() {
        /*
        Method
        ~~~~~~
        1.) Calls the diagnostic URL
        2.) NearBeach will pull data from the user table
        3.) If there is an issue, it will display it here
        4.) If there is no issue, it will green the row and change the text to "Successful"
         */
        $("#test_location_services").css("background-color","lightblue");
        $("#test_location_services td")[1].append("Running Test...");


        $.ajax({
            url: '/diagnostic_test_location_services/',
            type: 'GET',
            datatype: 'HTML',
            data: {},
            success: function(data) {
                $("#test_location_services td")[1].innerHTML = "Test Successful";
                $("#test_location_services").css("background-color", "lightgreen");
            },
            error: function (jqXHR, exception) {
                /*
                Email failed. The reason will be written here.
                */
                var error_message = '';

                if (jqXHR.status === 0) {
                    error_message = 'No connection, please verify that you have a network connection.';
                } else if (jqXHR.status == 404) {
                    error_message = '404 returned - please check to make sure that the connection to the email server is existing';
                } else if (jqXHR.status == 500) {
                    error_message = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    error_message = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    error_message = 'Time out error.';
                } else if (exception === 'abort') {
                    error_message = 'Ajax request aborted.';
                } else {
                    error_message = `There was a database error<br/>~~~~~~~~~~~<br/>${jqXHR.responseText}`;
                }
                $('#test_location_services td')[1].innerHTML = error_message;
                $("#test_location_services").css("background-color", "red");
                },
        });
    }

    function test_recaptcha() {
        /*
        Method
        ~~~~~~
        1.) Calls the diagnostic URL
        2.) NearBeach will pull data from the user table
        3.) If there is an issue, it will display it here
        4.) If there is no issue, it will green the row and change the text to "Successful"
         */
        $("#test_recaptcha").css("background-color","lightblue");
        $("#test_recaptcha td")[1].append("Running Test...");


        $.ajax({
            url: '/diagnostic_test_recaptcha/',
            type: 'GET',
            datatype: 'HTML',
            data: $("#test_recaptcha").serialize(),
            success: function(data) {
                $("#test_recaptcha td")[1].innerHTML = "Test Successful";
                $("#test_recaptcha").css("background-color", "lightgreen");
            },
            error: function (jqXHR, exception) {
                /*
                Email failed. The reason will be written here.
                */
                var error_message = '';

                if (jqXHR.status === 0) {
                    error_message = 'No connection, please verify that you have a network connection.';
                } else if (jqXHR.status == 404) {
                    error_message = '404 returned - please check to make sure that the connection to the email server is existing';
                } else if (jqXHR.status == 500) {
                    error_message = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    error_message = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    error_message = 'Time out error.';
                } else if (exception === 'abort') {
                    error_message = 'Ajax request aborted.';
                } else {
                    error_message = 'There was a database error\n~~~~~~~~~~~' + jqXHR.responseText;
                }
                $('#test_recaptcha td')[1].innerHTML = error_message;
                $("#test_recaptcha").css("background-color", "red");
                },
        });
    }

    function upload_document() {
        //Get form data
        var form_data = new FormData(document.querySelector('#document_upload'));

        $.ajax({
            xhr: function() {
                var xhr = new window.XMLHttpRequest();

                // Upload progress
                xhr.upload.addEventListener("progress", function(evt){
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        //Do something with upload progress
                        console.log(percentComplete);

                        $("#upload_percent").html(parseFloat(percentComplete * 100).toFixed(2) + "%");
                        $("#upload_progress").css(
                            'width', percentComplete * 100 + '%'
                        );
                    }
               }, false);
               return xhr;
            },

            url: '/diagnostic_test_document_upload/',
            data: form_data,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function(data) {
                $("#upload_percent").html("");
                $("#upload_progress").css("width","0%");
                $("#document_upload").html(data);
            },
            error: function (jqXHR, exception) {
                /*
                Email failed. The reason will be written here.
                */
                var error_message = '';

                if (jqXHR.status === 0) {
                    error_message = 'No connection, please verify that you have a network connection.';
                } else if (jqXHR.status == 404) {
                    error_message = '404 returned - please check to make sure that the connection to the email server is existing';
                } else if (jqXHR.status == 500) {
                    error_message = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    error_message = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    error_message = 'Time out error.';
                } else if (exception === 'abort') {
                    error_message = 'Ajax request aborted.';
                } else {
                    error_message = 'There was a database error\n~~~~~~~~~~~\n' + jqXHR.responseText;
                }
                $('#test_document_upload td')[1].innerHTML = error_message;
                $("#test_document_upload").css("background-color", "red");
                $("#upload_percent").html("");
                $("#upload_progress").css("width","0%");
            },
        });
    }

    function document_yes() {
        $('#test_document_upload td')[1].innerHTML = "Test Successful";
        $("#test_document_upload").css("background-color","lightgreen");
    }

    function document_no() {
        $('#test_document_upload td')[1].innerHTML = "Errors have been found";
        $("#test_document_upload").css("background-color", "red");
    }

</script>
</body>
{% endblock %}