"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const React = __importStar(require("react"));
const universal_cookie_1 = __importDefault(require("universal-cookie"));
const exenv_1 = __importDefault(require("exenv"));
const MEDIUM_USER_ID = require('../config/driver').keyMediumId;
exports.isLoggedIn = () => {
    const val = new universal_cookie_1.default().get(MEDIUM_USER_ID);
    //console.log("forceLogin: ",val);
    return val !== undefined;
};
const attach_request_1 = require("../../src/shared/components/attach-request");
//req.headers.cookie
// create a context with the default value: empty
const LoggedInContext = React.createContext(undefined);
/**
 * implements [[RequireServerRenderingSpec]]
 *
 * the ForceLogin Component is a HOC that passes the userid to its child components
 * the forceLogin gets the cookie value regardless on whether it runs on the server or in the browser
 * see: https://www.npmjs.com/package/universal-cookie
 *
 * see hocs with context: https://itnext.io/combining-hocs-with-the-new-reacts-context-api-9d3617dccf0b
 *
 * how to check whether running on server or in browser: https://www.npmjs.com/package/exenv
 */
class ForceLogin extends React.Component {
    /**
     * When we run in the browser: if not logged in, then make the page reload from the server to
     * make the login-middlewares apply
     */
    componentDidMount() {
        if (!exports.isLoggedIn()) {
            window.location.reload();
        }
    }
    render() {
        // we provide the information which user is logged in
        return React.createElement(LoggedInContext.Provider, { value: exenv_1.default.canUseDOM ?
                new universal_cookie_1.default().get(MEDIUM_USER_ID) :
                new universal_cookie_1.default(this.props.request.headers.cookie).get(MEDIUM_USER_ID) }, this.props.children);
    }
}
/**
 * Pass the information on whether the user `isLoggedIn` as prop to the component
 * @param Component
 * @returns {function(any): any}
 */
function withUserId(Component) {
    return function WrapperComponent(props) {
        return (React.createElement(LoggedInContext.Consumer, null, value => React.createElement(Component, Object.assign({}, props, { userId: value }))));
    };
}
exports.withUserId = withUserId;
exports.default = attach_request_1.withRequest(ForceLogin);
//# sourceMappingURL=force-login.js.map