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, Segment, Icon } from 'semantic-ui-react';

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

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

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

        const createdAt = formatInTimeZone(new Date(this.props.file.lastModified), DEFAULT_TIMEZONE, 'PPPp z');
        const fromNow = formatDistanceToNow(new Date(this.props.file.lastModified), { addSuffix: true });
        const isActive = this.props.activeRDC && (_.startsWith(this.props.activeRDC.build, this.props.file.build));

        return (
            <Table.Row positive={isActive}>
                <Table.Cell width={2}>
                    <Button size="small" href={this.props.file.url}><Icon name='download' />Download</Button>{this.props.file.build}
                    {isActive && <Label color="green">Active</Label>}
                </Table.Cell>
                <Table.Cell>
                    {this.props.file.size}
                </Table.Cell>
                <Table.Cell>
                    {fromNow}
                </Table.Cell>
                <Table.Cell>
                    <Button onClick={this.props.setActive}>Set Active</Button>
                </Table.Cell>
            </Table.Row>
        )
    }
}

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

    async componentDidMount() {
        await this.load();
    }

    async load() {
        this.setState({ loading: true });
        try {
            let res = await superagent.get(`/api/admin/rdc`).accept('json');
            let files = res.body.sort((a, b) => new Date(b.lastModified) - new Date(a.lastModified));
            this.setState({ files: res.body });
            res = await superagent.get(`/api/admin/rdc/active`).accept('json');
            this.setState({ activeRDC: res.body});
        } catch (e) {
            console.error(e);
        }
        this.setState({ loading: false });
    }

    async setRDCActive(build) {
        this.setState({ loading: true });
        const res = await superagent.put(`/api/admin/rdc/active/${build}`);
        await this.load();
    }

    render() {
        let activeClientBox = <div>Nothing active!</div>;
        if (this.state.activeRDC) {
            const timezone = "America/Los_Angeles";
            //const lastModified = formatInTimeZone(new Date(this.state.activeRDC.lastModified), DEFAULT_TIMEZONE, 'PPPp z');
            activeClientBox = (
                <Segment color="blue">
                    <Header>Active Version (Windows)</Header>
                    <Table compact celled>
                        <Table.Body>
                            <Table.Row>
                                <Table.Cell>Build:</Table.Cell>
                                <Table.Cell>{this.state.activeRDC.build}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Installer:</Table.Cell>
                                <Table.Cell>{this.state.activeRDC.installer}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Version:</Table.Cell>
                                <Table.Cell>{this.state.activeRDC.version}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Checksum:</Table.Cell>
                                <Table.Cell>{this.state.activeRDC.checksum}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Network:</Table.Cell>
                                <Table.Cell>{this.state.activeRDC.network || "not specified"}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Stage:</Table.Cell>
                                <Table.Cell>{this.state.activeRDC.stage}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Platform:</Table.Cell>
                                <Table.Cell>{this.state.activeRDC.platform}</Table.Cell>
                            </Table.Row>
                        </Table.Body>
                    </Table>
                    <Button primary href={this.state.activeRDC.url}><Icon name='download' />Download</Button>
                </Segment>
            );
        }
        return (
            <AppsWrapper title="Remote Desktop Client Installer" loading={this.state.loading}>
                {activeClientBox}
                <Table compact celled>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={2}>File</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Size (bytes)</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Last Modified</Table.HeaderCell>
                            <Table.HeaderCell width={1}></Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    
                    <Table.Body>
                    {this.state.files.map(file => {
                        return (
                            <RDCRow file={file} activeRDC={this.state.activeRDC} setActive={this.setRDCActive.bind(this, file.build)} />
                        );
                    })}
                    </Table.Body>
                </Table>
            </AppsWrapper>
        );
    }
}
