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

import {Button, Header, Label, Table, Image, Icon, Progress} from 'semantic-ui-react';

import NetworkWrapper from './NetworkWrapper.jsx';
import { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';

// This is an arbitrary estimate of the maximum number of peers per c5.large server.
const ESTIMATED_MAX_PEERS_PER_SERVER = 180.0;

class MediaServerRow extends React.Component {
    constructor(props) {
        super(props);
    }

    async setActivationStatus(activationStatus, e) {
        await superagent.put(`/cloud/admin/network/media-server/${this.props.server.mediaServerId}`).accept('json')
            .send({ activationStatus });
    }

    render() {
        if (!this.props.server) {
            return <div />;
        }

        const createdAt = formatInTimeZone(new Date(this.props.server.createdAt), DEFAULT_TIMEZONE, 'PPPp z');
        const uptime = formatDistanceToNow(new Date(this.props.server.createdAt));
        const status = <Label color={this.props.server.status === "OK" ? "green" : "orange"}>{this.props.server.status}</Label>;
        const activationStatus = this.props.server.activationStatus === "Retired" ? <Label color="grey">{this.props.server.activationStatus}</Label> : <span>✅</span>;
        const accelerated = this.props.server.isAccelerated && <Label color="violet"><Icon name="lightning" />Accelerated</Label>

        return (
            <Table.Row>
                <Table.Cell>
                    {activationStatus}
                </Table.Cell>
                <Table.Cell width={2}>
                    {this.props.server.name} {status}{accelerated}
                </Table.Cell>
                <Table.Cell>
                    {this.props.server.ipAddress}
                </Table.Cell>
                <Table.Cell>
                    {this.props.server.minPort}-{this.props.server.maxPort}
                </Table.Cell>
                <Table.Cell>
                    {this.props.server.instanceType} ({this.props.server.instanceId})
                </Table.Cell>
                <Table.Cell>
                    {this.props.server.region}
                </Table.Cell>
                <Table.Cell>
                    {this.props.server.load}
                </Table.Cell>
                <Table.Cell>
                    {(this.props.server.load / ESTIMATED_MAX_PEERS_PER_SERVER * 100.0).toFixed(1)}%
                </Table.Cell>
                <Table.Cell>
                    {uptime}
                </Table.Cell>
                <Table.Cell>
                    {this.props.server.activationStatus == "Active" && <Button onClick={this.setActivationStatus.bind(this, "Retired" )} color="grey" icon>Retire <Icon name="pause"/></Button>}
                    {this.props.server.activationStatus == "Retired" && <Button onClick={this.setActivationStatus.bind(this, "Active" )} color="blue" icon>Activate <Icon name="play"/></Button>}
                </Table.Cell>
            </Table.Row>
        )
    }
}

export default class MediaServers extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            servers: [],
            loading: false
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });
        const res = await superagent.get(`/cloud/admin/network/media-servers`).accept('json');
        console.log(res.body);
        this.setState({ loading: false, servers: res.body});
    }

    render() {
        const networkCapacity = this.state.servers.length * ESTIMATED_MAX_PEERS_PER_SERVER;
        const networkUsage = _.sum(this.state.servers.map(server => server.load));
        const capacityPercentage = (networkUsage / networkCapacity * 100.0).toFixed(1);

        return (
            <NetworkWrapper title="Media Servers" loading={this.state.loading}>

                <Header as="h3">Network Usage ({networkUsage}/{networkCapacity})</Header>
                <Progress percent={capacityPercentage} color='blue' progress />
                
                <Table compact celled>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={1}>Status</Table.HeaderCell>
                            <Table.HeaderCell width={2}>Server</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Public IP</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Port Range</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Server Type</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Region</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Current Connections</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Estimated Load</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Uptime</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Tools</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    
                    <Table.Body>
                    {this.state.servers.map(server => {
                        return (
                            <MediaServerRow server={server} />
                        );
                    })}
                    </Table.Body>
                </Table>
                <p>"Retired" - will serve active connections but won't take on new ones. Used before shutting down a server.</p>
            </NetworkWrapper>
        );
    }
}
