/* Coded by L1ghtM3n@protonmail.com */

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

// Run
function RunConverter() {
    // Get elements
    var json_area = document.getElementById("json_cookies");
    var netscape_area = document.getElementById("netscape_cookies");
    var json = JSON.stringify(ConvertCookies(netscape_area.value));
    // Change values
    netscape_area.value = '';
    json_area.value = json;
    // Resize text areas
    M.textareaAutoResize(netscape_area)
    M.textareaAutoResize(json_area)
}

// Convert Netscape cookies to Json format
function ConvertCookies(netscape) {
    var cookies = [];
    var lines = netscape.split("\n");
    // iterate over lines
    lines.forEach(function(line, index){
        var tokens = line.split("\t");
        // we only care for valid cookie def lines
        if (tokens.length == 7) {
            var cookie = {};
            // trim the tokens
            tokens = tokens.map(function(e) { return e.trim(); });
            // Extract the data
            cookie.domain = tokens[0];
            cookie.flag = tokens[1] === "TRUE";
            cookie.path = tokens[2];
            cookie.secure = tokens[3] === "TRUE";
            // Convert date to a readable format
            var timestamp = tokens[4];
            if (timestamp.length == 17){
            	timestamp = Math.floor(timestamp / 1000000 - 11644473600);
            }
            cookie.expiration = timestamp;
            cookie.name = tokens[5];
            cookie.value = tokens[6];
            // Save the cookie.
            cookies.push(cookie);
        }    
    });
    return cookies;
}