import { uuidV4 } from '@api-client/core/build/browser.js';
import { Events } from '../../events/Events.js';
import { HttpStore } from '../../store/HttpStore.js';
import { StoreBindings } from '../base/StoreBindings.js';
import { EnvironmentsKey } from '../base/ConfigurationBindings.js';
/**
 * API store bindings that handles communication with the store.
 */
export class WebStoreBindings extends StoreBindings {
    /**
     * @param storeBaseUri The base URI of the "local" store to be used when the user chooses
     * the local store over the
     */
    constructor(app, storeBaseUri) {
        super(app);
        this.environment = {
            init: async (init) => {
                const env = {
                    key: uuidV4(),
                    location: init.source === 'local-store' ? this.storeBaseUri : init.location,
                    name: init.name || 'New store',
                    source: init.source,
                    authenticated: false,
                };
                const store = new HttpStore(env);
                const info = await store.sdk.store.getInfo();
                const setDefault = init.reason === 'first-run' || !!init.asDefault;
                if (info.mode === 'single-user') {
                    // this store does not require authentication but does require setting up 
                    // a session.
                    await store.getStoreSessionToken(env);
                    // this event is handled by the application controller 
                    // and redirects the user to the next step.
                    await Events.Config.Environment.add(env, setDefault);
                }
                else if (init.reason === 'first-run') {
                    // the store needs authentication. We redirect the user to the 
                    // authentication screen.
                    await Events.Config.Session.set(`${EnvironmentsKey}.creating`, env);
                    Events.Navigation.Store.authenticate({ sameWindow: true });
                }
                else if (init.reason === 'add') {
                    // this is adding an environment from the configuration screen.
                    // We save the configuration in the store.
                    await Events.Config.Environment.add(env, setDefault);
                }
                // http://localhost:8487/v1/
                // http://localhost:8489/v1/
            },
            readStoreInfo: async (baseUri) => {
                const store = new HttpStore(baseUri);
                return store.sdk.store.getInfo();
            }
        };
        this.storeBaseUri = storeBaseUri;
    }
}
//# sourceMappingURL=WebStoreBindings.js.map