import { assembleLocString, parseLocString } from '@jbrowse/core/util';
import { onPatch } from '@jbrowse/mobx-state-tree';
import createModel from "./createModel/index.js";
export default function createViewState(opts) {
    const { assembly, tracks, internetAccounts, configuration, aggregateTextSearchAdapters, plugins = [], location, highlight, onChange, disableAddTracks = false, makeWorkerInstance, defaultSession, } = opts;
    const { model, pluginManager } = createModel(plugins, makeWorkerInstance);
    const stateTree = model.create({
        config: {
            configuration,
            assembly,
            tracks,
            internetAccounts,
            aggregateTextSearchAdapters,
        },
        disableAddTracks,
        session: defaultSession ?? {
            name: 'this session',
            view: {
                id: 'linearGenomeView',
                type: 'LinearGenomeView',
            },
        },
    }, { pluginManager });
    for (const account of stateTree.config.internetAccounts) {
        const internetAccountType = pluginManager.getInternetAccountType(account.type);
        if (!internetAccountType) {
            throw new Error(`unknown internet account type ${account.type}`);
        }
        stateTree.addInternetAccount({
            type: account.type,
            configuration: account,
        });
    }
    pluginManager.setRootModel(stateTree);
    pluginManager.configure();
    if (location) {
        ;
        (async () => {
            const { session } = stateTree;
            const { isValidRefName } = session.assemblyManager;
            try {
                await session.view.navToLocString(typeof location === 'string' ? location : assembleLocString(location), assembly.name);
                if (highlight) {
                    for (const h of highlight) {
                        if (h) {
                            const p = parseLocString(h, refName => isValidRefName(refName, assembly.name));
                            const { start, end } = p;
                            if (start !== undefined && end !== undefined) {
                                session.view.addToHighlights({
                                    ...p,
                                    start,
                                    end,
                                    assemblyName: assembly,
                                });
                            }
                        }
                    }
                }
            }
            catch (e) {
                session.notifyError(`${e}`, e);
            }
        })();
    }
    if (onChange) {
        onPatch(stateTree, onChange);
    }
    return stateTree;
}
