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

import { Segment, Header, Icon, Button, Table, Label, Modal, Message } from 'semantic-ui-react'
import { DEFAULT_TIMEZONE } from '../../CloudApi/Constants.js';
import _ from 'lodash';

export default class AccountDevices extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showBanDeviceDialog: false,
            pendingBanDeviceId: null,
            loading: false
        };
    }

    async componentDidMount() {
        return this.reload();
    }

    async reload() {
        try {
            this.setState({deviceHistory: null, loading: true});
            const deviceHistory = await superagent.get(`/api/admin/account/${this.props.account.id}/device_history`).accept('json');
            console.log(deviceHistory.body);

            this.setState({
                loading: false,
                deviceHistory: deviceHistory.body
            });
        } catch (e) {
            console.log(e);
            this.setState({
                loading: false,
                deviceHistory: null
            });
        }
    }

    // Ban device dialog
    onBanDeviceId( pendingBanDeviceId, e) {
        e.preventDefault();
        this.setState({showBanDeviceDialog: true, pendingBanDeviceId });
    }

    async onRemoveBannedDeviceId(deviceUniqueIdentifier, e) {
        e.preventDefault();
        try {
            const result = await superagent.put(`/api/admin/device/${deviceUniqueIdentifier}`).accept('json').send({
                status: "FullAccess"
            });
            return this.reload();
        } catch (e) {
            console.log(e);
        }
    }

    closeBanDeviceIdModal(e) {
        this.setState({showBanDeviceDialog: false, pendingBanDeviceId: null });
    }

    async onConfirmBanDeviceId(e) {
        e.preventDefault();

        try {
            const result = await superagent.put(`/api/admin/device/${this.state.pendingBanDeviceId}`).accept('json').send({
                status: "BannedFromEverything"
            });
            this.setState({showBanDeviceDialog: false, pendingBanDeviceId: null });
            return this.reload();
        } catch (e) {
            this.setState({showBanDeviceDialog: false, pendingBanDeviceId: null });
            console.log(e);
        }
    }

    render() {
        if (this.state.loading) {
            return (
                <Segment loading={true}>Loading...</Segment>
            )
        }

        if (this.state.deviceHistory == null || this.state.deviceHistory.devices == null || this.state.deviceHistory.devices.length == 0) {
            return (
                <Segment>No device history for this account. They've likely not logged in for a while.</Segment>
            )
        }

        const sortedDeviceList = _.orderBy(this.state.deviceHistory.devices, ["date._seconds"], ["desc"]);

        return (
            <div >
                <Modal dimmer="inverted" closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                    onClose={this.closeBanDeviceIdModal.bind(this)}
                    open={this.state.showBanDeviceDialog}>
                    <Header icon='user' content='Ban Device Identifier' />
                    <Modal.Content>
                        {
                            (this.props.account.status == "Ok") &&
                            <Message negative>
                                <Message.Header>Ban the user's account first!</Message.Header>
                                <Message.Content>
                                    Banning the account will kick the user out of public rooms.
                                </Message.Content>
                            </Message>
                        }

                        {
                            (this.props.account) &&
                            <p>Are you sure you want to ban the device id {this.state.pendingBanDeviceId}?</p>
                        }
                    </Modal.Content>
                    <Modal.Actions>
                        <Button color='red' onClick={this.onConfirmBanDeviceId.bind(this)}>
                            <Icon name='checkmark' />Yes, ban this device identifier!
                        </Button>
                    </Modal.Actions>
                </Modal>
                <Table celled>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={2}>Device</Table.HeaderCell>
                            <Table.HeaderCell width={2}>Status</Table.HeaderCell>
                            <Table.HeaderCell width={2}>GPU/CPU</Table.HeaderCell>
                            <Table.HeaderCell width={2}>OS</Table.HeaderCell>
                            <Table.HeaderCell width={2}>App Version</Table.HeaderCell>
                            <Table.HeaderCell width={2}>Last Date</Table.HeaderCell>
                            <Table.HeaderCell>Device ID</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {sortedDeviceList.map(device => {
                            let statusLabelColor = (device.status === "FullAccess") ? "green" : "red";
                            let dateString = "(n/a)";
                            if (device.date) {
                                if (device.date._seconds) {
                                    dateString = formatInTimeZone(fromUnixTime(device.date._seconds), DEFAULT_TIMEZONE, 'PPPp z');
                                } else if (_.isDate(device.date)) {
                                    dateString = formatInTimeZone(fromUnixTime(Date.parse(device.date)), DEFAULT_TIMEZONE, 'PPPp z');
                                }
                            }

                            return (
                            <Table.Row>
                                <Table.Cell width={2}>
                            <Label color="blue" basic>{device.deviceName || device.HMD}{(device.operatingSystem && _.startsWith(device.operatingSystem, "Android OS 10")) ? " 2" : ""}</Label>
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    <Label color={statusLabelColor}>{device.status}</Label>
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    <Header as='h4'>
                                        <Header.Content>
                                        {device.GPU}
                                        <Header.Subheader>{device.CPU}</Header.Subheader>
                                        </Header.Content>
                                    </Header>
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    {device.operatingSystem}
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    {device.version}
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    {dateString}
                                </Table.Cell>
                                <Table.Cell>
                                    {
                                        (device.status === "FullAccess") ?
                                        <Button color="red" onClick={this.onBanDeviceId.bind(this, device.deviceUniqueIdentifier)}><Icon name='ban' size="small" />Ban Device Id</Button> :
                                        <Button color="black" onClick={this.onRemoveBannedDeviceId.bind(this, device.deviceUniqueIdentifier)}><Icon name='ban' size="small" />Remove Device Ban</Button>
                                    }
                                    <br /><small>{device.deviceUniqueIdentifier}</small>
                                </Table.Cell>
                            </Table.Row>
                            )
                        })}

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