import React from 'react';
import superagent from 'superagent';
import { fromUnixTime, formatDistanceToNow } from "date-fns";

import constants from '../CloudApi/Constants.js';
import RoomComponent from './RoomComponent.jsx';
import { RoomsUpdater, RoomData } from './RoomsUpdater.jsx';
import RoomsTable from './RoomsTable.jsx';
import * as ApiUtils from '../CloudApi/ApiUtils.js';

import { 
    Accordion,
    Segment,
    Grid,
    Header,
    Image,
    Icon,
    Button,
    Table,
    Form,
    Divider,
    Label,
    Modal,
    Statistic,
    Radio } from 'semantic-ui-react'

export default class RoomsPanel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loadingRooms: false,
            activeIndex: -1,
            selectedRoomIndex: 0,
            statistics: {
                onlineUserCount: 0,
                roomCount: 0
            },
            autoUpdate: true,
            usersInChannels: 0,
            lastUpdated: "",
            environmentOptions: null
        };
    }

    async componentDidMount() {
        const environmentOptions = await ApiUtils.getEnvironmentOptions();
        this.setState({ environmentOptions });
    }

    async refreshRoomData() {
    }

    async roomsUpdated() {
        this.setState({ loadingRooms: RoomData.isLoading });
    }

    async onSwitchAutoUpdater() {
        const autoUpdate = !this.state.autoUpdate;
        this.setState({ autoUpdate });
        if (autoUpdate) {
            await this.refreshData();
            this.autoUpdater = setInterval(this.refreshData.bind(this), 5000);
        } else {
            clearTimeout(this.autoUpdater);
            this.autoUpdater = null;
        }
    }

    async showSetRoomPrivateModal() {
    }

    onMakeRoomPrivate(e) {
        e.preventDefault();

        let rooms = RoomData.rooms;
        let roomId = rooms[this.state.selectedRoomIndex].roomId;
        rooms.splice(this.state.selectedRoomIndex, 1);
        this.setState({ rooms, isShowingSetRoomPrivateModal: false });

        superagent.get(`/api/delete_room/${roomId}`).accept('json').end(function(err, res) {
            console.log("Deleted room!");
        }.bind(this));
    }

    closeDeleteRoomModal(e) {
        this.setState({isShowingSetRoomPrivateModal: false});
    }

    onUpdateRoom(roomIndex, event, { name, value }) {
        console.log(roomIndex, event, name, value);
        event.preventDefault();
        
        let rooms = RoomData.rooms;
        let room = rooms[roomIndex];

        if (room) {
            let payload = {};
            payload[name] = value;

            room[name] = value;

            rooms[roomIndex] = room;
            this.setState({ rooms });
            
            superagent.put(`/cloud/admin/room/${room.roomId}`).send(payload).accept('json').end(function(err, res) {
                console.log("updated room");
            }.bind(this));
        }
    }

    onVerify(event) {
        event.preventDefault();
    }

    getChannelRoomUsersCount() {
        let channelRoomUsers = 0;
        for (const room of RoomData.tvRooms) {
            channelRoomUsers += (room.participants ? room.participants : 0);
        }
        return channelRoomUsers;
    }

    getPrivateRoomsCount() {
        return RoomData.statistics.roomCount - (RoomData.statistics.publicRoomCount + RoomData.statistics.friendsOnlyRoomCount);
    }

    getPublicRoomsUserCount() {
        let publicRoomUsers = 0;
        for (const room of RoomData.rooms) {
            publicRoomUsers += (room.participantsIndex ? Object.keys(room.participantsIndex).length : 0);
        }
        for (const room of RoomData.tvRooms) {
            publicRoomUsers += (room.participantsIndex ? Object.keys(room.participantsIndex).length : 0);
        }
        for (const room of RoomData.lobbyRooms) {
            publicRoomUsers += (room.participantsIndex ? Object.keys(room.participantsIndex).length : 0);
        }
        return publicRoomUsers;
    }

    getPrivateRoomsUserCount() {
        let publicRoomUsers = this.getPublicRoomsUserCount();
        return RoomData.statistics.onlineUserCount - (publicRoomUsers);
    }

    totalPublicRoomUsersInfo() {
        let publicRoomUserCount =this.getPublicRoomsUserCount();
        let percent = 0.0;
        if (RoomData.statistics.onlineUserCount > 0) {
            percent = Math.round((publicRoomUserCount/RoomData.statistics.onlineUserCount) * 100);
        }
        
        return `${publicRoomUserCount} (${percent}%)`;
    }

    render() {
        /*const roomsSummary = (
            <Table size="small" celled striped>
                <Table.Header fullWidth>
                    <Table.Row widths="equal">
                        <Table.HeaderCell collapsing>Name</Table.HeaderCell>
                        <Table.HeaderCell collapsing>Info</Table.HeaderCell>
                        <Table.HeaderCell collapsing>Environment</Table.HeaderCell>
                        <Table.HeaderCell collapsing>Owner</Table.HeaderCell>
                        <Table.HeaderCell collapsing>Category</Table.HeaderCell>
                        <Table.HeaderCell collapsing>Created</Table.HeaderCell>
                        <Table.HeaderCell>Tools</Table.HeaderCell>
                    </Table.Row>
                </Table.Header>

                <Table.Body>
                    {RoomData.rooms.map((room, roomIndex) => this.renderCompactRoomInfo(room, roomIndex))}
                </Table.Body>
            </Table>
        );*/

        return (
            <div>
                <a name={"top"} />
                <RoomsUpdater roomUpdateCallback={this.roomsUpdated.bind(this)} />
                <Modal 
                    dimmer="inverted"
                    closeOnEscape={this.closeDeleteRoomModal.bind(this)}
                    closeOnDimmerClick={this.closeDeleteRoomModal.bind(this)}
                    onClose={this.closeDeleteRoomModal.bind(this)}
                    open={this.state.isShowingSetRoomPrivateModal} closeIcon>
                    <Header icon='archive' content='Make Room Private' />
                    <Modal.Content>{
                        (RoomData.rooms.length > 0 && this.state.selectedRoomIndex < RoomData.rooms.length) &&
                        <p>Are you sure you want to set the room {RoomData.rooms[this.state.selectedRoomIndex].name} ({RoomData.rooms[this.state.selectedRoomIndex].roomId}) to private?</p>
                    }
                    </Modal.Content>
                    <Modal.Actions>
                        <Button color='green' onClick={this.onMakeRoomPrivate.bind(this)}>
                            <Icon name='checkmark' />Yes, Make Room Private.
                        </Button>
                    </Modal.Actions>
                </Modal>
                <Segment basic floated="right">
                    <Button size="small" disabled={this.state.loading || this.state.autoUpdate} circular icon="refresh" onClick={this.refreshRoomData.bind(this)} />&nbsp;
                    <Radio toggle label='Auto Update' checked={this.state.autoUpdate} disabled={this.state.loading} onChange={this.onSwitchAutoUpdater.bind(this)} />
                </Segment>
                <Statistic.Group size="small">
                    <Statistic>
                        <Statistic.Value>
                        {RoomData.statistics.onlineUserCount}</Statistic.Value>
                        <Statistic.Label>Users</Statistic.Label>
                    </Statistic>
                    
                    <Statistic>
                        <Statistic.Value>
                            {this.getPrivateRoomsUserCount()}
                        </Statistic.Value>
                        <Statistic.Label>Private Room Users</Statistic.Label>
                    </Statistic>
                    
                    <Statistic>
                        <Statistic.Value>
                            {RoomData.statistics.roomCount}
                        </Statistic.Value>
                        <Statistic.Label>All Rooms</Statistic.Label>
                    </Statistic>
                    
                    <Statistic>
                        <Statistic.Value>
                            {RoomData.rooms.length}
                        </Statistic.Value>
                        <Statistic.Label>Public Rooms</Statistic.Label>
                    </Statistic>
                    
                    <Statistic>
                        <Statistic.Value>
                            {RoomData.statistics.friendsOnlyRoomCount}
                        </Statistic.Value>
                        <Statistic.Label>Friends Only Rooms</Statistic.Label>
                    </Statistic>
                    
                    <Statistic>
                        <Statistic.Value>
                            {this.getPrivateRoomsCount()}
                        </Statistic.Value>
                        <Statistic.Label>Private Rooms</Statistic.Label>
                    </Statistic>

                    <Statistic>
                        <Statistic.Value>
                            {this.totalPublicRoomUsersInfo()}
                        </Statistic.Value>
                        <Statistic.Label>Public Room Users</Statistic.Label>
                    </Statistic>
                </Statistic.Group>

                <Segment basic>
                    <Header as="h2">Latest Rooms</Header>
                    <RoomsTable rooms={RoomData.rooms} environmentOptions={this.state.environmentOptions} onUpdateRoom={this.onUpdateRoom} showSetRoomPrivateModal={this.showSetRoomPrivateModal} />
                </Segment>

                <Divider clearing />

                <a name={"tv-rooms"} />
                <Divider clearing />
                <Segment basic loading={RoomData.isLoading}>
                    <Header as="h2">TV Rooms</Header>
                    {RoomData.tvRooms.map((room, roomIndex) => {
                        return (<RoomComponent 
                            compact
                            room={room} 
                            roomIndex={roomIndex}
                            environmentOptions={this.state.environmentOptions}
                        />);
                    })}
                </Segment>

                <a name={"public-rooms"} />
                <Divider clearing />
                <Segment basic loading={RoomData.isLoading}>
                    <Header as="h2">Detailed Public Rooms</Header>
                    {RoomData.rooms.map((room, roomIndex) => {
                        return (
                            <RoomComponent 
                                room={room} compact
                                roomIndex={roomIndex}
                                environmentOptions={this.state.environmentOptions}
                                onUpdateRoom={this.onUpdateRoom.bind(this)}
                            />
                        );
                    })}
                </Segment>

                <a name={"lobby-rooms"} />
                <Divider clearing />
                <Segment basic loading={RoomData.isLoading}>
                    <Header as="h2">Lobbies</Header>
                    {RoomData.lobbyRooms.map((room, roomIndex) => {
                        return (<RoomComponent 
                            room={room} compact
                            roomIndex={roomIndex}
                            environmentOptions={this.state.environmentOptions}
                        />);
                    })}
                </Segment>
            </div>
        );
    }
}
