import { unsetToken } from "./auth";

const getAuth0 = () => {
    const auth0 = require("auth0-js");
    return new auth0.WebAuth({
        clientID: "zVCyO6gVAwTV4WWQdhFm9XwGPKdNc3za",
        domain: "jkp.auth0.com",
    });
};

const getBaseUrl = () => `${window.location.protocol}//${window.location.host}`;

const getOptions = () => {
    return {
        responseType: "token id_token",
        redirectUri: `${getBaseUrl()}/auth`,
        scope: "openid profile email",
    };
};

export const login = () => {
    window.localStorage.setItem("auth_return", window.location.href);
    getAuth0().authorize(getOptions());
};

export const logout = () => {
    unsetToken();
    getAuth0().logout({ returnTo: getBaseUrl() });
};
export const parseHash = async () => {
    const auth_return = window.localStorage.getItem("auth_return");
    window.localStorage.removeItem("auth_return");

    const return_prom = new Promise<{
        auth_info: {
            idToken: string,
            accessToken: string,
        },
        auth_return: string,
    }>((resolve, reject) => {
        getAuth0().parseHash((err: any, result: { idToken: string; accessToken: string; }) => {
            if (err) {
                reject(err);
            }

            resolve({
                auth_info: result,
                auth_return,
            });
        });
    });

    return return_prom;

};
