"use strict";

function load_all_records(dbtable, related_table, record_id, element_id, order,
                          request) {
    let xhttp = new XMLHttpRequest();

    let record = document.getElementById(element_id);
    let record_table = record.getElementsByClassName("related_tables")[0];

    let loader = document.createElement("div");
    loader.className = "loader";
    let load_button = document.getElementById('js-load-all-records:' + element_id);

    let error_message = load_button.nextSibling;
    error_message.classList.add("hidden");

    xhttp.onreadystatechange = function() {
        if(xhttp.readyState === XMLHttpRequest.DONE) {
            if(xhttp.status === 0 || (xhttp.status === 200 && status < 400)) {
                record_table.remove(loader);
                record_table.style.opacity = "1.0";
                load_button.disabled = false;

                let record_updated =
                    new DOMParser().parseFromString(this.responseText, 'text/html');

                const element_id_re =
                      new RegExp(dbtable + ":0" + "." + related_table, "igm");
                const element_id_multifk_re =
                      new RegExp(dbtable + ":0" + "." + related_table + '\.\w+', "igm");

                const attributes_to_update =
                      [ "id", "name", "htmlFor", "value", "onclick", "onchange" ];

                record_updated.querySelectorAll("*[id], *[name], *[htmlFor], *[value], " +
                                                "*[onclick], *[onchange]")
                              .forEach(function(element){
                    attributes_to_update.forEach(function(attribute){
                        let attribute_value = element.getAttribute(attribute);
                        if(typeof attribute_value !== 'undefined' &&
                           attribute_value !== null &&
                           attribute_value !== "") {
                            if(element.classList.contains('js-button')){
                                // Unhiding buttons due to Ajax inability to re-run
                                // Javascript by default.
                                element.style = "";
                            }
                            if(attribute_value.search(element_id_multifk_re)) {
                                element.setAttribute(
                                    attribute,
                                    attribute_value.replace(element_id_multifk_re,
                                                            element_id)
                                );
                            } else {
                                element.setAttribute(
                                    attribute,
                                    attribute_value.replace(element_id_re,
                                                            element_id)
                                );
                            }
                        }
                    });
                });

                // Checks if there is tabular dbdata in order to replace only rows of
                // data not header.
                let is_terminal_tabular = false;
                record.childNodes.forEach(function(rec){
                    let rec_class_list = rec.classList;
                    if(typeof rec_class_list !== 'undefined' &&
                       rec_class_list.contains("dbdata-tabular")) {
                        is_terminal_tabular = true;
                        return;
                    }
                });

                if(is_terminal_tabular) {
                    record.getElementsByTagName("tbody")[0].innerHTML =
                        record_updated.getElementById(element_id)
                                      .getElementsByTagName("tbody")[0].innerHTML;
                } else {
                    record.innerHTML =
                        record_updated.getElementById(element_id).innerHTML;
                }

                // After Ajax the response callback, select2 is not initialized so,
                // it is being here.
                if($('.dropdown').hasClass("select2-hidden-accessible")) {
                    $('.dropdown').select2({dropdownAutoWidth: true});
                }

                // Modifying 'rows' parameter in order to have compatable data merge between
                // data structure in CGI script and Javascript-generated one.
                let rows = document.createElement("input");
                rows.setAttribute("name", "rows");
                rows.setAttribute("value", "-1");
                rows.setAttribute("style", "display: none");
                record.appendChild(rows);
            }
        } else if(xhttp.status >= 400) {
            record_table.removeChild(loader);
            record_table.style.opacity = "1.0";
            load_button.disabled = false;
            error_message.innerHTML =
                "<p> <b>" + this.statusText + "</b> <br>" +
                "HTTP Status " + this.status + "</p>";
            error_message.classList.remove("hidden");
        } else {
            record_table.style.opacity = "0.5";
            record_table.append(loader);
            load_button.disabled = true;
        }
    }

    // Modify href to view specific records.
    let record_url = window.location.href;
    let record_url_parts = record_url.split("/");
    record_url_parts.pop();
    record_url_parts.pop();
    record_url_parts.push(dbtable);
    record_url_parts.push(record_id);
    record_url = record_url_parts.join("/");

    if(request === "POST") {
        let requestData = new FormData();
        requestData.append("Edit", "Edit");
        requestData.append("format", "htmlblock");
        requestData.append("rows", "-1");
        requestData.append("related_table", related_table);
        xhttp.open(request, record_url, true);
        xhttp.setRequestHeader('Content-Type', 'multipart/form-data');
        xhttp.send(requestData);
    } else if(request === "GET") {
        let request_uri = record_url + "?format=htmlblock";
        if(typeof order !== "undefined") {
            request_uri += "&order=" + order;
        }
        request_uri += "&rows=" + "-1" +
                       "&related_table=" + related_table +
                       "#" + element_id;
        xhttp.open(request, request_uri, true);
        xhttp.send();
    }
}
