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

import { fromUnixTime } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz'

import { Header, Segment } from 'semantic-ui-react'
import { DEFAULT_TIMEZONE } from '../../CloudApi/Constants.js';
import RoomsTable from '../../Rooms/RoomsTable.jsx';
import * as ApiUtils from '../../CloudApi/ApiUtils.js';

export default class AccountRooms extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            rooms: [],
            roomCount: 0
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });
        try {
            const environmentOptions = await ApiUtils.getEnvironmentOptions();
            this.setState({ roomHistory: [], environmentOptions });        

            const res = await superagent.get(`/cloud/admin/rooms/all?ownerBigscreenAccountId=${this.props.account.id}`).accept('json');
            const storedRooms = res.body.items;
            const storedRoomsCount = res.body.count;

            const res2 = await superagent.get(`/cloud/admin/rooms/live?ownerBigscreenAccountId=${this.props.account.id}`).accept('json');
            const liveRooms = res2.body;
            const combinedRooms = storedRooms.map(storedRoom => {
                const liveRoom = liveRooms.find(liveRoom => liveRoom.roomId === storedRoom.roomId);
                if (!liveRoom) {
                    return storedRoom;
                }
                
                if (!liveRoom.storedRoomSnapshot) {
                    liveRoom.storedRoomSnapshot = storedRoom;
                }
                return liveRoom;
            });
            this.setState({ roomCount: storedRoomsCount, rooms: combinedRooms });
        } catch (e) {
            console.log(e);
        }
        this.setState({ loading: false });
    }

    render() {
        if (this.state.loading) {
            return <Segment basic loading={this.state.loading}>&nbsp;</Segment>
        }

        if (this.state.roomCount === 0) {
            return <Segment basic>No rooms found.</Segment>
        }

        return (<>
            <Header as='h2'>Rooms</Header>
            <RoomsTable rooms={this.state.rooms} environmentOptions={this.state.environmentOptions} extra />
        </>);
    }
}
