import React from 'react';
import ReactDOM from 'react-dom';
import { initSdk } from '@hiro-ui/sdk';
import HiroGraphOrm from '@hiro-graph/orm';
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 } = {}) {
        this.setup = async () => {
            const { ready, config: { token, graphUrl }, } = await initSdk(this.config);
            let orm;
            if (token && graphUrl) {
                orm = new HiroGraphOrm({
                    endpoint: graphUrl,
                    token,
                }, HiroGraphMappings);
            }
            return { orm, ready };
        };
        this.render = async (children, target) => {
            const { orm, ready } = await this.setup();
            ReactDOM.render(React.createElement(HiroAppRoot, { orm: orm }, children), target, ready);
        };
        this.config = config;
        if (!config) {
            this.config = getConfigFromEnv();
        }
    }
}
