export function setCookie(name, value, expireDays, host, encode) {
    if (name == null) {
        return;
    }
    let extra = `; domain=${host ?? location.hostname}; path=/`;
    if (expireDays != null) {
        const d = new Date();
        d.setTime(d.getTime() + (expireDays * 24 * 60 * 60 * 1000));
        extra += `; expires=${d.toGMTString()}`;
    }
    if (/^(https|wss):$/.test(location.protocol)) {
        extra += '; secure';
    }
    if (encode !== false) {
        value = encodeURIComponent(value);
    }
    document.cookie = `${name}=${value}${extra}`;
}

export function getCookie(name) {
    if (name == null) {
        return null;
    }
    name += '=';
    const cookies = document.cookie.split(';');
    for (let cookie of cookies) {
        cookie = cookie.trim();
        if (cookie.startsWith(name)) {
            return decodeURIComponent(cookie.substring(name.length));
        }
    }
    return null;
}

export function deleteCookie(name) {
    setCookie(name, '', -1);
}