import React from "react";
import ReactDOM from "react-dom";
import { initSdk } from "@hiro-ui/sdk";
import HiroGraphOrm from "@hiro-graph/orm";
import { init } from "../stores";
import { HiroAppRoot } from "../components";
import { getMappings } from "../helpers";
const HiroGraphMappings = getMappings();
const getConfigFromEnv = () => {
    const graphUrl = process.env.REACT_APP_GRAPH_URL;
    const authUrl = process.env.REACT_APP_AUTH_URL || `${graphUrl}/api/6/auth/ui/`;
    const redirectUrl = process.env.REACT_APP_REDIRECT_URL || `${graphUrl}/api/6/auth/ui-redirect`;
    const clientId = process.env.REACT_APP_CLIENT_ID;
    const config = {
        graphUrl,
        authUrl,
        clientId,
        redirectUrl
    };
    if (Object.values(config).every(Boolean)) {
        return config;
    }
    return undefined;
};
export class HiroApp {
    constructor({ config, reducers, sagas } = {}) {
        this.setup = async () => {
            const { ready, state, token, graphUrl } = await initSdk(this.config);
            let orm;
            if (token && graphUrl) {
                orm = new HiroGraphOrm({
                    endpoint: graphUrl,
                    token
                }, HiroGraphMappings);
            }
            const store = init({
                state,
                reducers: this.reducers,
                sagas: this.sagas,
                orm
            });
            return { store, orm, ready };
        };
        this.render = async (children, target) => {
            const { store, orm, ready } = await this.setup();
            ReactDOM.render(React.createElement(HiroAppRoot, { store: store, orm: orm }, children), target, ready);
        };
        this.config = config;
        this.reducers = reducers;
        this.sagas = sagas;
        if (!config) {
            this.config = getConfigFromEnv();
        }
    }
}
