<commit_before>// Show refresh button and overlay
var isLoading;

// Org Units data in JSON forms
var orgUnits;
var parentChildOUs;

// Search criteria
var searchName;

// Display criteria
var layerLimitNum;
var totalLayers;

/*
 * Initially loads the page, fetching all OUs and adding search events.
 */
async function onloadOUPage() {
    loginStatus();

    var searchButton = document.getElementById("search-enter-btn");
    searchButton.addEventListener("click", function(event) {
        searchName = searchBar.value;
        d3.select("svg").remove();
        getAllOUs();
    })

    var searchBar = document.getElementById("search");
    // Execute a function when the user presses enter or erases the input
    searchBar.addEventListener("search", function(event) {
        searchButton.click();
    });

    orgUnits = await fetchOUs();
    layerLimitNum = parseInt(document.getElementById("limit-layer-num").value);

    getAllOUs();
}

/*
 * Used to refresh the page upon deletion, creation, or update of OUs.
 */
async function refreshOUPage() {
    loginStatus();

    document.getElementById("search").value = '';
    searchName = '';

    // either remove the no-search-result-element or the visualization
    noSearchResultScreen = document.getElementById('no-search-result-elem');
    if (noSearchResultScreen) {
        noSearchResultScreen.remove();
    } else {
        d3.select("svg").remove();
    }

    orgUnits = await fetchOUs();
    layerLimitNum = parseInt(document.getElementById("limit-layer-num").value);

    getAllOUs();
}

/*
 * Fetches all OUs from the Admin SDK.
*/
async function fetchOUs() {
    // fetch all OUs from API
    try {
        const response = await fetch('https://www.googleapis.com/admin/directory/v1/customer/my_customer/orgunits?orgUnitPath=/&type=all', {
            headers: {
                'authorization': `Bearer ` + token,
            }
        });
        const directoryOUs = await response.json();
        orgUnits = directoryOUs['organizationUnits'];
        return orgUnits;
    } catch (error) {
        console.error('Error:', error);
    }
}

/*
 * Calls all the functions to manipulate OU data, and loads the sidebar and visualization.
*/
function getAllOUs() {
    isLoading = true;
    setLoadingOverlay();
    var limitedOUs = orgUnits;

    // Limit Layers always runs unless no search match, Search runs only if a query has been made
    if (searchName) {
        var searchedOU = searchOU(searchName);

        if (searchedOU) {
            // compile all parents of the searched org unit
            limitedOUs = [];
            var parentOrgUnitPath = searchedOU['parentOrgUnitPath'];
            parentArr = parentOrgUnitPath.split('/');
            // first elem is always empty
            parentArr.shift();

            // need to match OUs by paths (which are unique) rather than by names
            var pathSoFar = '';

            while (parentArr.length != 0) {
                pathSoFar = pathSoFar + '/' + parentArr.shift();
                for (var i = 0; i < orgUnits.length; i++) {
                    if (orgUnits[i]['orgUnitPath'] == pathSoFar) {
                        limitedOUs.push(orgUnits[i]);
                        break;
                    }
                }
            }

            // no sort needed, as OUs added in order of increasing depth
            limitedOUs.push(searchedOU);
        } else {
            limitedOUs = []
            loadSidebar(limitedOUs);
            noSearchResult();
            
            return;
        }
    }

    // limit layers code
    limitedOUs.sort(ouDepthSort); // sort by depth
    limitedOUs = limitLayers(limitedOUs);

    loadSidebar(limitedOUs);
    parentChildOUs = constructD3JSON(limitedOUs); // transform into parent-child JSON
    visualize(parentChildOUs); // visualize with D3
    addListeners();
}

/*
 * Constructs the no matching search results screen.
 */
function noSearchResult() {
    if (document.getElementById("no-search-result-elem")) {
        isLoading = false;
        setLoadingOverlay();
        return;
    }
    var div = document.createElement("div");
        div.classList.add("no-search-results");
        div.id = "no-search-result-elem";
        var p = document.createElement("P");
        p.innerHTML = "There were no results for your search."; 
        var btn = document.createElement("BUTTON");
        btn.innerHTML = "Reset all";
        btn.classList.add("btn");
        btn.classList.add("btn-primary");
        btn.onclick = refreshOUPage;

        div.appendChild(p);
        div.appendChild(btn);
        document.getElementById('chart-container').append(div);

        // loading is over
        isLoading = false;
        setLoadingOverlay();
}

/*
 * Returns a list of OUs within the layer depth limit.
*/
function limitLayers(limitedOUs) {
    if (limitedOUs.length == 0) {
        return [];
    }
    var lastElementDepth = computeDepth(limitedOUs[limitedOUs.length - 1]);
    // set the totalLayers global var
    totalLayers = lastElementDepth;
    if (totalLayers <= layerLimitNum) {
        return limitedOUs;
    } else {
        limitedOUList = [];
        for (var i = 0; i < limitedOUs.length; i++) {
            currentOU = limitedOUs[i];
            if (computeDepth(currentOU) > layerLimitNum) {
                break;
            }
            limitedOUList.push(currentOU);
        }
        return limitedOUList;
    }
}

/* Fill in informational fields on the sidebar of the page */
function loadSidebar(limitedOUs) {
    const domainName = document.getElementById("domain-name");
    domainName.innerHTML = "@" + domain;

    const displayOUs = document.getElementById("display-ous");
    const displayLayers = document.getElementById("display-layers");
    const totalOUs = document.getElementById("total-ous");
    const totalLayerCount = document.getElementById("total-layers");

    var displayLimit = document.getElementById("limit-layer-num");
    displayLimit.setAttribute("max", totalLayers);
    <commit_msg>readability changes (mostly for loops)<commit_after>// Show refresh button and overlay
var isLoading;

// Org Units data in JSON forms
var orgUnits;
var parentChildOUs;

// Search criteria
var searchName;

// Display criteria
var layerLimitNum;
var totalLayers;

/*
 * Initially loads the page, fetching all OUs and adding search events.
 */
async function onloadOUPage() {
    loginStatus();

    var searchButton = document.getElementById("search-enter-btn");
    searchButton.addEventListener("click", function(event) {
        searchName = searchBar.value;
        d3.select("svg").remove();
        getAllOUs();
    })

    var searchBar = document.getElementById("search");
    // Execute a function when the user presses enter or erases the input
    searchBar.addEventListener("search", function(event) {
        searchButton.click();
    });

    orgUnits = await fetchOUs();
    layerLimitNum = parseInt(document.getElementById("limit-layer-num").value);

    getAllOUs();
}

/*
 * Used to refresh the page upon deletion, creation, or update of OUs.
 */
async function refreshOUPage() {
    loginStatus();

    document.getElementById("search").value = '';
    searchName = '';

    // either remove the no-search-result-element or the visualization
    noSearchResultScreen = document.getElementById('no-search-result-elem');
    if (noSearchResultScreen) {
        noSearchResultScreen.remove();
    } else {
        d3.select("svg").remove();
    }

    orgUnits = await fetchOUs();
    layerLimitNum = parseInt(document.getElementById("limit-layer-num").value);

    getAllOUs();
}

/*
 * Fetches all OUs from the Admin SDK.
*/
async function fetchOUs() {
    // fetch all OUs from API
    try {
        const response = await fetch('https://www.googleapis.com/admin/directory/v1/customer/my_customer/orgunits?orgUnitPath=/&type=all', {
            headers: {
                'authorization': `Bearer ` + token,
            }
        });
        const directoryOUs = await response.json();
        orgUnits = directoryOUs['organizationUnits'];
        return orgUnits;
    } catch (error) {
        console.error('Error:', error);
    }
}

/*
 * Calls all the functions to manipulate OU data, and loads the sidebar and visualization.
*/
function getAllOUs() {
    isLoading = true;
    setLoadingOverlay();
    var limitedOUs = orgUnits;

    // Limit Layers always runs unless no search match, Search runs only if a query has been made
    if (searchName) {
        var searchedOU = searchOU(searchName);

        if (searchedOU) {
            // compile all parents of the searched org unit
            limitedOUs = [];
            var parentOrgUnitPath = searchedOU['parentOrgUnitPath'];
            parentArr = parentOrgUnitPath.split('/');
            // first elem is always empty
            parentArr.shift();

            // need to match OUs by paths (which are unique) rather than by names
            var pathSoFar = '';

            while (parentArr.length != 0) {
                pathSoFar = pathSoFar + '/' + parentArr.shift();

                for (unit of orgUnits) {
                    if (unit['orgUnitPath'] == pathSoFar) {
                        limitedOUs.push(unit);
                        break;
                    }
                }
            }

            // no sort needed, as OUs added in order of increasing depth
            limitedOUs.push(searchedOU);
        } else {
            limitedOUs = []
            loadSidebar(limitedOUs);
            noSearchResult();
            
            return;
        }
    }

    // limit layers code
    limitedOUs.sort(ouDepthSort); // sort by depth
    limitedOUs = limitLayers(limitedOUs);

    loadSidebar(limitedOUs);
    parentChildOUs = constructD3JSON(limitedOUs); // transform into parent-child JSON
    visualize(parentChildOUs); // visualize with D3
    addListeners();
}

/*
 * Constructs the no matching search results screen.
 */
function noSearchResult() {
    if (document.getElementById("no-search-result-elem")) {
        isLoading = false;
        setLoadingOverlay();
        return;
    }
    var div = document.createElement("div");
    div.classList.add("no-search-results");
    div.id = "no-search-result-elem";
    var p = document.createElement("P");
    p.innerHTML = "There were no results for your search."; 
    var refreshOUPageButton = document.createElement("BUTTON");
    refreshOUPageButton.innerHTML = "Reset all";
    refreshOUPageButton.classList.add("btn");
    refreshOUPageButton.classList.add("btn-primary");
    refreshOUPageButton.onclick = refreshOUPage;

    div.appendChild(p);
    div.appendChild(refreshOUPageButton);
    document.getElementById('chart-container').append(div);

    // loading is over
    isLoading = false;
    setLoadingOverlay();
}

/*
 * Returns a list of OUs within the layer depth limit.
*/
function limitLayers(limitedOUs) {
    if (limitedOUs.length == 0) {
        return [];
    }
    var lastElementDepth = computeDepth(limitedOUs[limitedOUs.length - 1]);
    // set the totalLayers global var
    totalLayers = lastElementDepth;
    if (totalLayers <= layerLimitNum) {
        return limitedOUs;
    } else {
        limitedOUList = [];

        for (current of limitedOUs) {
            if (computeDepth(current) > layerLimitNum) {
                break;
            }
            limitedOUList.push(current);
        }

        return limitedOUList;
    }
}

/* Fill in informational fields on the sidebar of the page */
function loadSidebar(limitedOUs) {
    const domainName = document.getElementById("domain-name");
    domainName.innerHTML = "@" + domain;

    const displayOUs = document.getElementById("display-ous");
    const displayLayers = document.getElementById("display-layers");
    const totalOUs = document.getElementById("total-ous");
    const totalLayerCount = document.getElementById("total-layers");

    var displayLimit = document.getElementById("limit-layer-num");
    displayLimit.setAttribute("max", totalLayers);
    
{'fraction_non_alphanumeric': 0.11256631299734748, 'fraction_numerical': 0.0014920424403183023, 'mean_word_length': 2.4679505605058925, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3502255', 'n_tokens_mistral': 3374, 'n_tokens_neox': 3245, 'n_words': 840}