import { InfinityMintClient } from './client';
import { InfinityMintClientConfig } from './core/interfaces';
import storageController from './core/storage';

let globalConfig: InfinityMintClientConfig;
let currentClient: InfinityMintClient;

export function setConfig(config: InfinityMintClientConfig) {
    globalConfig = config;
}

export function getConfig(): InfinityMintClientConfig {
    return globalConfig;
}

export async function reload(config?: InfinityMintClientConfig) {
    config = config || globalConfig;
    if (currentClient) {
        let client = currentClient;
        client.destroy();
        client.config = config;
        await client.load();
        return client;
    } else return await load(config);
}

export async function load(
    config: InfinityMintClientConfig
): Promise<InfinityMintClient> {
    if (currentClient)
        throw new Error('InfinityMintClient is already initialized');

    setConfig(config);
    //load storage once global config is set
    storageController.load();
    let client = new InfinityMintClient(config);

    await client.load();
    currentClient = client;
    return client;
}

export const hasCurrentClient = () => {
    return !!currentClient;
};

export const getCurrentClient = () => {
    return currentClient;
};
