"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SolidAuthnLogic = void 0;
const rdflib_1 = require("rdflib");
const authUtil_1 = require("./authUtil");
const debug = __importStar(require("../util/debug"));
const solid_client_authn_browser_1 = require("@inrupt/solid-client-authn-browser");
class SolidAuthnLogic {
    session;
    constructor(solidAuthSession) {
        this.session = solidAuthSession;
    }
    // we created authSession getter because we want to access it as authn.authSession externally
    get authSession() { return this.session; }
    currentUser() {
        const app = (0, authUtil_1.appContext)();
        if (app.viewingNoAuthPage) {
            return (0, rdflib_1.sym)(app.webId);
        }
        if (this && this.session && this.session.info && this.session.info.webId && this.session.info.isLoggedIn) {
            return (0, rdflib_1.sym)(this.session.info.webId);
        }
        return (0, authUtil_1.offlineTestID)(); // null unless testing
    }
    /**
     * Retrieves currently logged in webId from either
     * defaultTestUser or SolidAuth
     * Also activates a session after login
     * @param [setUserCallback] Optional callback
     * @returns Resolves with webId uri, if no callback provided
     */
    async checkUser(setUserCallback) {
        // Save hash for "restorePreviousSession"
        const preLoginRedirectHash = new URL(window.location.href).hash;
        if (preLoginRedirectHash) {
            window.localStorage.setItem('preLoginRedirectHash', preLoginRedirectHash);
        }
        this.session.events.on(solid_client_authn_browser_1.EVENTS.SESSION_RESTORED, (url) => {
            debug.log(`Session restored to ${url}`);
            if (document.location.toString() !== url)
                history.replaceState(null, '', url);
        });
        /**
         * Handle a successful authentication redirect
         */
        const redirectUrl = new URL(window.location.href);
        redirectUrl.hash = '';
        await this.session
            .handleIncomingRedirect({
            restorePreviousSession: true,
            url: redirectUrl.href
        });
        // Check to see if a hash was stored in local storage
        const postLoginRedirectHash = window.localStorage.getItem('preLoginRedirectHash');
        if (postLoginRedirectHash) {
            const curUrl = new URL(window.location.href);
            if (curUrl.hash !== postLoginRedirectHash) {
                if (history.pushState) {
                    // debug.log('Setting window.location.has using pushState')
                    history.pushState(null, document.title, postLoginRedirectHash);
                }
                else {
                    // debug.warn('Setting window.location.has using location.hash')
                    location.hash = postLoginRedirectHash;
                }
                curUrl.hash = postLoginRedirectHash;
            }
            // See https://stackoverflow.com/questions/3870057/how-can-i-update-window-location-hash-without-jumping-the-document
            // window.location.href = curUrl.toString()// @@ See https://developer.mozilla.org/en-US/docs/Web/API/Window/location
            window.localStorage.setItem('preLoginRedirectHash', '');
        }
        // Check to see if already logged in / have the WebID
        let me = (0, authUtil_1.offlineTestID)();
        if (me) {
            return Promise.resolve(setUserCallback ? setUserCallback(me) : me);
        }
        const webId = this.webIdFromSession(this.session.info);
        if (webId) {
            me = this.saveUser(webId);
        }
        if (me) {
            debug.log(`(Logged in as ${me} by authentication)`);
        }
        return Promise.resolve(setUserCallback ? setUserCallback(me) : me);
    }
    /**
     * Saves `webId` in `context.me`
     * @param webId
     * @param context
     *
     * @returns Returns the WebID, after setting it
     */
    saveUser(webId, context) {
        let webIdUri;
        if (webId) {
            webIdUri = (typeof webId === 'string') ? webId : webId.uri;
            const me = (0, rdflib_1.namedNode)(webIdUri);
            if (context) {
                context.me = me;
            }
            return me;
        }
        return null;
    }
    /**
     * @returns {Promise<string|null>} Resolves with WebID URI or null
     */
    webIdFromSession(session) {
        const webId = session?.webId && session.isLoggedIn ? session.webId : null;
        return webId;
    }
}
exports.SolidAuthnLogic = SolidAuthnLogic;
//# sourceMappingURL=SolidAuthnLogic.js.map