// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

import {Database} from '@nozbe/watermelondb';
import DatabaseProvider from '@nozbe/watermelondb/DatabaseProvider';
import React, {ComponentType, useEffect, useState} from 'react';

import ServerProvider from '@context/server';
import ThemeProvider from '@context/theme';
import UserLocaleProvider from '@context/user_locale';
import DatabaseManager from '@database/manager';
import {subscribeActiveServers} from '@database/subscription/servers';

import type ServersModel from '@typings/database/models/app/servers';

type State = {
    database: Database;
    serverUrl: string;
    serverDisplayName: string;
};

export function withServerDatabase<T>(Component: ComponentType<T>): ComponentType<T> {
    return function ServerDatabaseComponent(props) {
        const [state, setState] = useState<State | undefined>();

        const observer = (servers: ServersModel[]) => {
            const server = servers?.length ? servers.reduce((a, b) =>
                (b.lastActiveAt > a.lastActiveAt ? b : a),
            ) : undefined;

            if (server) {
                const serverDatabase =
                    DatabaseManager.serverDatabases[server?.url]?.database;

                setState({
                    database: serverDatabase,
                    serverUrl: server?.url,
                    serverDisplayName: server?.displayName,
                });
            } else {
                setState(undefined);
            }
        };

        useEffect(() => {
            const subscription = subscribeActiveServers(observer);

            return () => {
                subscription?.unsubscribe();
            };
        }, []);

        if (!state?.database) {
            return null;
        }

        return (
            <DatabaseProvider database={state.database}>
                <UserLocaleProvider database={state.database}>
                    <ServerProvider server={{displayName: state.serverDisplayName, url: state.serverUrl}}>
                        <ThemeProvider database={state.database}>
                            <Component {...props}/>
                        </ThemeProvider>
                    </ServerProvider>
                </UserLocaleProvider>
            </DatabaseProvider>
        );
    };
}
