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

import { Segment, Table, Label } from 'semantic-ui-react'
import { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';

export default class Logs extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            logs: [],
        };
    }

    async componentDidMount() {
        try {
            this.setState({ loading: false, logs: [] });
            const res = await superagent.get(`/api/admin/logs`).accept('json');
            console.log(res.body);
            const logs = res.body;
            this.setState({ logs });
        } catch (e) {
            console.log(e);
        }
    }

    render() {
        if (this.state.logs == null || this.state.logs.length == 0) {
            return (
                <div>No logs!</div>
            )
        }

        const logs = _.orderBy(this.state.logs, ["timestamp"], ["desc"]);

        return (
            <Table celled striped compact>
                <Table.Header>
                    <Table.Row>
                        <Table.HeaderCell width={3} collapsing>Date</Table.HeaderCell>
                        <Table.HeaderCell width={2} collapsing>Message</Table.HeaderCell>
                    </Table.Row>
                </Table.Header>
                <Table.Body>
                    {logs.map(log => {
                        return (
                        <Table.Row>
                            <Table.Cell width={3} collapsing>
                                {formatInTimeZone(fromUnixTime(log.timestamp / 1000), DEFAULT_TIMEZONE, 'PPPp z')}
                            </Table.Cell>
                            <Table.Cell width={2}>
                                <pre>
                                    {log.message}
                                </pre>
                            </Table.Cell>
                        </Table.Row>
                        )
                    })}

                </Table.Body>
            </Table>
        );
    }
}
