import { action, computed, observable } 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 { StrCast } from '../../fields/Types';
import { Doc } from '../../fields/Doc';
import { SettingsManager } from './SettingsManager';

@observer
export class ServerStats extends React.Component<{}> {
    public static Instance: ServerStats;
    @observable private isOpen = false; // whether the SharingManager modal is open or not

    // private get linkVisible() {
    //     return this.targetDoc ? this.targetDoc["acl-" + PublicKey] !== SharingPermissions.None : false;
    // }

    @action
    public open = async () => {
        /**
         * Populates the list of users.
         */
        fetch('/stats').then((res: Response) => res.text().then(action(stats => (this._stats = JSON.parse(stats)))));

        this.isOpen = true;
    };

    public close = action(() => {
        this.isOpen = false;
    });

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

    @observable _stats: { [key: string]: any } | undefined;

    /**
     * @returns the main interface of the SharingManager.
     */
    @computed get sharingInterface() {
        return (
            <div
                style={{
                    display: 'flex',
                    height: 300,
                    width: 400,
                    background: SettingsManager.Instance?.userBackgroundColor,
                    opacity: 0.6,
                }}>
                <div style={{ width: 300, height: 100, 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: any) => (
                        <p>{user.username}</p>
                    ))}
                </div>
            </div>
        );
    }

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