import Logger from "@insite/client-framework/Logger";
import { getSessionCookies, setSessionCookies } from "@insite/client-framework/ServerSideRendering";
import { setupGetCookie, setupSetCookie } from "@insite/mobius/utilities/cookies";
import { SafeDictionary } from "@insite/client-framework/Common/Types";
import Cookies, { CookieAttributes } from "js-cookie";

export function getCookie(name: string) {
    if (IS_SERVER_SIDE) {
        const cookies = getSessionCookies();
        if (cookies) {
            const cookieValue = cookies[name];
            if (cookieValue) {
                return decodeCookie(cookieValue);
            }
        }
        return;
    }
    return getCookies().get(name);
}

setupGetCookie(getCookie);

export function setCookie(name: string, value: string, options?: CookieAttributes) {
    if (IS_SERVER_SIDE) {
        let cookies = getSessionCookies();
        if (!cookies) {
            cookies = {} as SafeDictionary<string>;
        }
        cookies[name] = encodeCookie(value);
        setSessionCookies(cookies);
        return;
    }

    const isSecure = window.location.protocol === "https:";
    if (options) {
        options.secure = isSecure;
    } else {
        options = { secure: isSecure };
    }

    return getCookies().set(name, value, options);
}

setupSetCookie(setCookie);

export function removeCookie(name: string, options?: CookieAttributes) {
    if (IS_SERVER_SIDE) {
        const cookies = getSessionCookies();
        if (!cookies || !cookies[name]) {
            return;
        }

        delete cookies[name];
        setSessionCookies(cookies);
        return;
    }

    const isSecure = window.location.protocol === "https:";
    if (options) {
        options.secure = isSecure;
    } else {
        options = { secure: isSecure };
    }

    return Cookies.remove(name, options);
}

function getCookies() {
    return Cookies.withConverter({
        read: decodeCookie,
        write: value => encodeCookie(value.toString()),
    });
}

// on the .net site we use HttpUtility.UrlEncode which encodes ' ' as '+'
export function decodeCookie(value: string) {
    return decodeURIComponent(value.replace(/\+/g, " "));
}

export function encodeCookie(value: string) {
    return encodeURIComponent(value.toString()).replace(/%20/g, "+");
}
