import TelemetryDeck from '@telemetrydeck/sdk';


///////////////
// TELEMETRY //
///////////////

// Telemetry Deck only collects fully anonymized data!

const getCookieValueOrNull = (name) => {
    const cookie = document.cookie
        .split(";")
        .map(c => c.trim())
        .find(c => c.startsWith(name + "="));
    return cookie ? cookie.split("=")[1] : null;
};

function getOrCreateUUID() {
    let cookie_val = getCookieValueOrNull("id");
    if (
        cookie_val
    ) {
        return cookie_val;
    } else {
        let uuid =crypto.randomUUID();
        const days = 365;
        const expires = new Date(Date.now() + days * 864e5).toUTCString();
        document.cookie = `id=${uuid}; expires=${expires}`;
        return uuid;
    }
}

// Send Test Signals when running locally
function init() {
    const appId = "E453AAB8-B1AD-4F3E-87DF-97FC3A0400B9";
    if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
        const td = new TelemetryDeck({
            appID: appId,
            clientUser: getOrCreateUUID(),
            testMode: true
        });
        return td;
    } else {
        const td = new TelemetryDeck({
            appID: appId,
            clientUser: getOrCreateUUID()
        });
        return td;
    }
}

let td = init();


export function send(type, payload) {
    td.signal(type, payload);
}
