import React from 'react';
import superagent from 'superagent';

export const RoomData = {
    rooms: [],
    tvRooms: [],
    lobbyRooms: [],
    statistics: {},
    isLoading: false,
    roomsUpdater: null
};

// Component that continually updates room data.
export class RoomsUpdater extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loadingRooms: false
        };
    }

    async refreshData() {
        if (RoomData.isLoading) {
            return;
        }

        RoomData.isLoading = true;

        if (this.props.roomUpdateCallback) {
            this.props.roomUpdateCallback();
        }

        try {
            let res = await Promise.all([
                superagent.get('/cloud/admin/statistics').accept('json'),
                superagent.get('/cloud/admin/rooms/live').accept('json'),
                superagent.get("/cloud/admin/rooms/live?roomType=tv").accept('json'),
                superagent.get('/cloud/admin/rooms/live?roomType=lobby').accept('json')
            ]);

            RoomData.statistics = res[0].body;

            let rooms = res[1].body;
            rooms.sort((a, b) => a.storedRoomSnapshot.name.localeCompare(b.storedRoomSnapshot.name));
            RoomData.rooms = rooms;

            if (_.isArray(res[2].body)) {
                RoomData.tvRooms = res[2].body;
            }
            if (_.isArray(res[3].body)) {
                RoomData.lobbyRooms = res[3].body;
            }
        } catch (err) {
            console.error(err);
        }
        
        RoomData.isLoading = false;

        if (this.props.roomUpdateCallback) {
            this.props.roomUpdateCallback();
        }
    }

    static async stopRoomsUpdater() {
        const autoUpdate = !this.state.autoUpdate;
        this.setState({ autoUpdate });
        if (autoUpdate) {
            await this.refreshData();
            roomsUpdater = setInterval(this.refreshData.bind(this), 5000);
        } else {
            roomsUpdater = null;
        }
    }

    async componentDidMount() {
        await this.refreshData();
        if (RoomData.roomsUpdater) {
            clearTimeout(RoomData.roomsUpdater);
        }
        RoomData.roomsUpdater = setInterval(this.refreshData.bind(this), 5000);
    }
    
    render() {
        return null;
    }
}
