import { action, computed, makeObservable, observable, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { MainViewModal } from '../views/MainViewModal';
import './SharingManager.scss';
import { PingManager } from './PingManager';
import { SettingsManager } from './SettingsManager';

/**
 * NOTE: this must be kept in synch with UserStats definition in server's DashStats.ts file
 * UserStats holds the stats associated with a particular user.
 */
interface UserStats {
    socketId: string;
    username: string;
    time: string;
    operations: number;
    rate: number;
}
@observer
export class ServerStats extends React.Component<object> {
    // eslint-disable-next-line no-use-before-define
    public static Instance: ServerStats;
    @observable private isOpen = false; // whether the SharingManager modal is open or not

    @observable _stats: { socketMap: UserStats[]; currentConnections: number } | undefined = undefined;
    // private get linkVisible() {
    //     return this.targetDoc ? this.targetDoc['acl_' + PublicKey] !== SharingPermissions.None : false;
    // }

    constructor(props: object) {
        super(props);
        makeObservable(this);
        ServerStats.Instance = this;
    }

    /**
     * @returns the main interface of the SharingManager.
     */
    @computed get sharingInterface() {
        return (
            <div
                style={{
                    display: 'flex',
                    height: '100%',
                    width: 400,
                    background: SettingsManager.userBackgroundColor,
                    opacity: 0.6,
                }}>
                <div style={{ width: 300, margin: 'auto', display: 'flex', flexDirection: 'column' }}>
                    {PingManager.Instance.IsBeating ? 'The server connection is active' : 'The server connection has been interrupted.NOTE: Any changes made will appear to persist but will be lost after a browser refreshes.'}

                    <br />
                    <span>Active users:{this._stats?.socketMap.length}</span>
                    {this._stats?.socketMap.map(user => <p key={user.username}>{user.username}</p>)}
                </div>
            </div>
        );
    }

    // eslint-disable-next-line react/sort-comp
    public close = action(() => {
        this.isOpen = false;
    });
    public open = async () => {
        /**
         * Populates the list of users.
         */
        fetch('/stats').then((res: Response) =>
            res.text().then(
                action(stats => {
                    this._stats = JSON.parse(stats);
                })
            )
        );

        runInAction(() => {
            this.isOpen = true;
        });
    };

    render() {
        return <MainViewModal contents={this.sharingInterface} isDisplayed={this.isOpen} interactive closeOnExternalClick={this.close} />;
    }
}
