(function($) {
    'use strict';
    const api_prefix = "https://scan.onlineada.com";
    const domain = ada_plugin.home_url;
    var scan_details;
    var metabox;
    const chunkSize = ada_plugin.chunkSize;

    $("document").ready(function() {
        if (ada_plugin.pagenow == "edit-wcag_scan") {
            if (window.location.href.match(/post_status=future/)) {
                $(".subsubsub").remove();
                $("#menu-posts-wcag_scan .current").removeAttr("class").removeAttr("aria-current");
                $("#menu-posts-wcag_scan [href='edit.php?post_status=future&post_type=wcag_scan']")
                    .attr("aria-current", "page")
                    .parent().attr("class", "current");
            } else {
                $(".subsubsub .all, .subsubsub .future").remove();
                $(".subsubsub li:not(.trash):not(.publish)").hide();
                $(".subsubsub .publish a").attr("href", "/wp-admin/edit.php?post_type=wcag_scan");
                if ($(".subsubsub .publish a .count").length > 0) {
                    let count = $(".subsubsub .publish a .count")[0].outerHTML;
                    $(".subsubsub .publish a").html("Completed " + count);
                }

                let a = $(".subsubsub .publish a");
                if ($(".subsubsub .trash").length < 1) {
                    $(".subsubsub .publish").html(a);
                }
            }
        }
        $.each($("#menu-posts-wcag_scan a"), function() {
            if ($(this).attr("href").match(/^http/)) {
                $(this).attr("target", "_blank");
            }
        });

        $(".free-banner .dismiss a").on("click", function(e) {
            e.preventDefault();
            $.ajax({
                url: ada_plugin.ajaxurl,
                method: "POST",
                data: {
                    action: "_oadaas__dismiss_free_banner",
                    security: ada_plugin.security
                },
                success: function(re) {
                    $(".free-banner").hide();
                }
            });
        });

        $('#wcag-scan-schedule').on('change', function() {
            let highlight_area = $(this).next();
            highlight_area.toggleClass('schedule-enabled', $(this).val() != '');
        }).trigger('change');


        $('.wcag-checklist').on("change", "input:checkbox", function() {
            $(this).closest('.wcag-checklist-item').toggleClass('checklist-checked', $(this).prop('checked'));
        });

        $('.wcag-checklist input:checkbox:checked').trigger("change");

        if (typeof document.querySelector('.wcag-scan-progress-in-progress') !== null) {
            keep_scan_progress_on_top();
        }

        $('.ada-plugin-start-scan-button').on("click", function() {
            var input = $('#ada_plugin_start_scan');
            input.val(input.attr('data-nonce'));
            $('#post').submit();
        });

        /* SET AUTOMATIC TITLE OF NEW SCAN */
        if (typeof ada_plugin.pagenow != "undefined" && ada_plugin.pagenow == "wcag_scan") {
            var title = $('#title');
            let today = new Date();
            let date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
            title.val("Audit " + date).trigger('change').trigger('keydown');
        }

        ada_plugin_refresh_progress_metabox();

        $('.wcag-save-and-continue-button').on("click", function() {
            if ($(this).length < 1) return;
            $(this).closest("form").submit();
        });

        /* DISMISS MESSAGE LOGIC */
        $("body").on('click', '.dismiss-message', function(e) {
            e.preventDefault();

            // Remember that this menu was dismissed
            $.ajax({
                url: ajaxurl,
                method: "GET",
                data: {
                    action: "_oadaas__dismiss_scan",
                    security: ada_plugin.security
                }
            });

            //Remove the notice
            $(this).closest('div.wcag-notice').animate({
                opacity: 0
            }, {
                duration: 300,
                complete: function() {
                    $(this).hide();
                }
            });
            return false;
        });
    });

    function keep_scan_progress_on_top() {
        var scan_progress = $('#wcag_scan_progress');
        if (scan_progress.length < 1) return;

        var sortable_div = scan_progress.parent('.meta-box-sortables');
        if (sortable_div.length < 1) return;

        var placeMetaboxOnTop = function() {
            if (scan_progress.index() > 0) {

                sortable_div.prepend(scan_progress);
            }
        };

        placeMetaboxOnTop();

        sortable_div.on('sortstop', placeMetaboxOnTop);
    }

    function ada_plugin_refresh_progress_metabox() {
        metabox = $('.wcag-progress');
        if (metabox.length < 1) return;

        // Only run this code if the metabox is in progress
        if (!metabox.is('.wcag-progress-in-progress')) return;

        // Do not run this code if the update mode is set to "refresh".
        if (metabox.find('.wcag-progress-mode-refresh').length > 0) return;

        process_scan();
    }

    function stop_processing(retry = false) {
        metabox.removeClass('ajax-processing').removeClass('ajax-refreshing').addClass('ajax-stopped');
        if (retry) {
            setTimeout(refresh_metabox(), retry)
        }
    };

    /* MOST LOGIC FOR THE SCAN (STEPS AND METABOXES) HAPPENS HERE */
    function process_scan() {
        metabox.addClass('ajax-processing').removeClass('ajax-refreshing').removeClass('ajax-stopped');

        // Process a scan
        $.ajax({
            url: ada_plugin.ajaxurl,
            data: {
                action: '_oadaas__get_scan_details',
                security: ada_plugin.security
            },
            success: function(data) {
                var data = JSON.parse(data);
                scan_details = data;

                //Data has the sitemap array
                if (metabox.is('.stop-ajax')) {
                    return stop_processing();
                } // allows interruption of the ajax responses
                if (typeof scan_details == "object") {
                    if (scan_details["status"] == "complete") {
                        stop_processing();
                        if (ada_plugin.current_screen.id == "wcag_scan") {
                            window.location.reload();
                        }
                    }

                    //Process ada-scan steps
                    /* STEP 1 */
                    if (scan_details.scan_step === "ada-scan") {
                        //Stop running scan if there is no sitemap
                        if (Object.keys(scan_details.sitemap).length === 0) {
                            return stop_processing();
                        }
                        let complete = scan_details.pages_remaining.length == 0;
                        if (!complete) {
                            call_scan_api();
                        }
                        if (complete) {
                            mark_scan_step_complete();
                        }
                    }

                    //Process colorblind steps
                    /* STEP 2 */
                    if (scan_details.scan_step == "color-blind-report") {
                        //check for if color blind report was asked for
                        if (Number(scan_details._oadaas_include_cbr) > 0) {
                            let filter_step = Number(scan_details.filter_step);
                            if (filter_step === 0) {
                                start_colorblind_report();
                            }

                            if (filter_step > 0 && filter_step < 10) {
                                get_filter();
                            }
                            if (filter_step === 10) {
                                get_snapshot();
                            }
                        }

                        //If color blind report was not asked for
                        if (Number(scan_details._oadaas_include_cbr) === 0) {
                            get_snapshot();
                        }
                    }

                    if (scan_details.scan_step === "scan_finished") {
                        mark_scan_step_complete();
                    }
                } else {
                    // The result was not successful. Give an error and stop processing.
                    stop_processing();

                    console.log('Invalid response from server. See response data below:');
                    console.log(scan_details);

                    alert('Invalid response from server, expected a successful response (integer: 1). See JavaScript console for details.');
                }
            }
        });
    };

    function get_snapshot() {
        $.post({
            url: api_prefix + "/webservice/v1/snapshot",
            data: {
                domain: domain,
                height: 800
            },
            success: (re) => {
                var data = {
                    store: re,
                    action: "_oadaas__save_chunks",
                    security: ada_plugin.security,
                    name: 'snapshot'
                };
                
                chunk(data, re);
                return;
            }
        });
    }

    var refresh_metabox = function() {
        if (metabox.is('.stop-ajax')) return stop_processing();

        metabox.addClass('ajax-refreshing').removeClass('ajax-processing').removeClass('ajax-stopped');

        /* ENSURES THE SCAN CONTINUES TO RUN IN THE BACKGROUND, WE DUMP THE ID TO THE PROGRESS METABOX */
        var scan_id = $('#post_ID').val();
        if (typeof scan_id == "undefined") {
            scan_id = jQuery('#wcag_scan_id').val();
        }
        $.ajax({
            url: ada_plugin.ajaxurl,
            type: "POST",
            data: {
                action: '_oadaas__update_progress_metabox',
                scan_id: scan_id,
                is_scan_screen: ada_plugin.current_screen.id,
                security: ada_plugin.security
            },
            success: function(data) {

                //Progress partial view gets updated based on the scan step. It passes the scan then sets the html appropriately and gets returned here
                var view = $(data);

                if (metabox.is('.stop-ajax')) return stop_processing(); // allows interruption of the ajax responses

                if (view.is('.wcag-progress')) {
                    if (view.find('.wcag-progress-mode-refresh').length > 0 && ada_plugin.current_screen.id == "wcag_scan") {
                        // If the progress mode is set to "refresh", reload the page. This means the widget is not supposed to update with ajax anymore.
                        stop_processing();
                        window.location.reload();
                        return;
                    }

                    if (view.hasClass('wcag-progress-complete')) {
                        stop_processing();
                        if (ada_plugin.current_screen.id == "wcag_scan") {
                            window.location.reload();
                        }
                        metabox.replaceWith(view);
                        return;
                    }
                    metabox.children('.wcag-scan-progress-indicator').replaceWith(view.children('.wcag-scan-progress-indicator'));
                    view.remove();
                } else {
                    // The response did not include the metabox. Give an error, stop processing.
                    stop_processing();

                    console.log('Invalid response from server. See response data below:');
                    console.log(data);

                    //alert('Invalid response from server, expected update to progress widget. See JavaScript console for details.');
                }

                // Shortly afterwards, continue processing
                setTimeout(process_scan, 1000);
            }
        });
    };

    function splitData(str, length) {
        if(str === undefined) return false;
        return str.match(new RegExp('.{1,' + length + '}', 'g'));
    }

    var call_scan_api = function() {
        let page = scan_details.pages_remaining[0];
        let license = ada_plugin.license || "free";
        var split = ada_plugin.home_url.split("://");

        $.ajax({
            url: api_prefix+"/webservice/v1/scan",
            method: "POST",
            data: {
                page: page,
                protocol: split[0],
                domain: split[1],
                license: license,
            },
            success: function(response) {
                if (response.hasOwnProperty("error")) {
                    stop_processing();
                    console.group("Error");
                    console.log("Error: " + response.error);
                    console.log("Message: " + response.details);
                    console.groupEnd();
                    alert("The audit returned an error. Please see the console for more details");
                }

                if (license != "free" && response.scan_type == "free") {
                    alert("Your license was not validated so it has been switched to audit only your homepage. To unlock full site auditing please provide a valid license key.");
                }

                let toSend = "no results";
                
                if (!$.isEmptyObject(response.data)) {
                    toSend = JSON.stringify(response.data);
                    toSend = encodeURIComponent(toSend); //<-- Necessary for b64 encoding non UTF-8 characters
                    toSend = btoa(toSend); //<-- Base64 encoding the string

                    var data = {
                        store: toSend,
                        page: page,
                        action: "_oadaas__save_chunks",
                        security: ada_plugin.security,
                        name: 'scan_results'
                    };

                    chunk(data, response);
                    return;
                }
                //There was no data returned
                mark_empty_page_scanned(page, response.scan_type);


            },
            error: function(re) {
                console.log(re);
                stop_processing();
                if ($(".wcag-scan-progress-indicator").length) {
                    $(".wcag-scan-progress-indicator").find(".col-description .content").html("<div style='font-size:20px;font-weight:bold;'>The audit has run into a problem. Please check the console for more information</div>");
                }
                //there was a problem
            }
        });
    }

    function mark_empty_page_scanned(page, scan_type) {

        $.ajax({
            url: ada_plugin.ajaxurl,
            data: {
                action: "_oadaas__empty_results",
                page: page,
                security: ada_plugin.security
            },
            success: function(re) {
                if (scan_type == "free") {
                    mark_scan_step_complete();
                    return;
                } else {
                    refresh_metabox();
                    return;
                }
            },
            error: function(re) {
                //there was a problem
            }
        });
    }

    //The API has to create the first filter differently than the rest using puppeteer to take a snapshot of the domain. That is why we don't use get_filter() for the first one.
    function start_colorblind_report() {

        $.ajax({
            url: api_prefix+"/webservice/v1/cbc/" + scan_details.scan_id + "/init",
            type: "POST",
            data: {
                domain: domain
            },
            success: function(response) {
                if (response === "success") {
                    update_filter_step();
                }
            },
        });
    }

    function update_filter_step() {
        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: {
                action: '_oadaas__update_filter_step',
                security: ada_plugin.security
            },
            complete: function(response) {
                refresh_metabox();
            }
        });
    }

    function get_filter() {
        $.ajax({
            url: api_prefix+'/webservice/v1/cbc/' + scan_details.scan_id + "/" + Number(scan_details.filter_step) + "/create_filter",
            data: {},
            type: "GET",
            success: function(re) {

                var data = {
                    store: re["b64es"],
                    filter_name: re["filter_name"],
                    action: "_oadaas__save_chunks",
                    security: ada_plugin.security,
                    name: 'filter'
                };

                chunk(data, re);
                return;
            },
            error: function(re){
                console.log("Only here if there was an error!!", re);
            }
        });
    }

    function chunk(data, response) {
        var chunkedData = splitData(data.store, chunkSize);
        data.chunks = chunkedData.length;
        var index = 0;
        saveChunks(data, chunkedData, index, response.scan_type);
        return;
    }

    function saveChunks(data, chunkedData, index, scan_type) {
        if (index < data.chunks) {
            data.store = chunkedData[index];
            data.current_chunk = index;
            $.ajax({
                url: ada_plugin.ajaxurl,
                data: data,
                type: "POST",
                success: function(response) {
                    index++;
                    saveChunks(data, chunkedData, index, scan_type);
                },
                error: function(response) {
                    console.log(response);
                    stop_processing();
                }
            });
        } else {
            if (data.name == "scan_results" && scan_type == "free") {
                mark_scan_step_complete();
                return;
            }
            if (data.name == "scan_results" && scan_type == "paid") {
                refresh_metabox();
                return;
            }
            if (data.name == "filter") {
                update_filter_step();
                return;
            }
            if (data.name == "snapshot") {
                mark_scan_step_complete();
                return;
            }
        }
    }

    function mark_scan_step_complete() {
        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: {
                action: '_oadaas__mark_complete',
                security: ada_plugin.security
            },
            success: function(re) {
                refresh_metabox();
            },
            error: function() {},
            complete: function(re) {}
        });
    }
})(jQuery);

// Automatically cancel unfinished ajax requests
// when the user navigates elsewhere.
(function($) {
    var xhrPool = [];
    $(document).ajaxSend(function(e, jqXHR, options) {
        xhrPool.push(jqXHR);
    });
    $(document).ajaxComplete(function(e, jqXHR, options) {
        xhrPool = $.grep(xhrPool, function(x) {
            return x != jqXHR
        });
    });
    var abort = function() {
        $.each(xhrPool, function(idx, jqXHR) {
            jqXHR.abort();
        });
    };

    var oldbeforeunload = window.onbeforeunload;
    window.onbeforeunload = function() {
        var r = oldbeforeunload ? oldbeforeunload() : undefined;
        if (r == undefined) {
            // only cancel requests if there is no prompt to stay on the page
            // if there is a prompt, it will likely give the requests enough time to finish
            abort();
        }
        return r;
    }
})(jQuery);