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

import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants';

import {
    Radio,
    Segment,
    Header,
    Image,
    Modal,
    Icon,
    Button,
    Table,
    Form,
    Label, Dropdown } from 'semantic-ui-react'

export default class ScreenComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentMediaProduct: null,
            isShowingDeleteScreenModal: false
        };
    }

    async componentDidMount() {
        if (this.props.room.content) {
            const contentJSON = JSON.parse(decodeURIComponent(this.props.room.content));
            let bigMediaId = contentJSON.bigMediaId;
            const res = await superagent.post("/api/admin/media/query").send( { bigMediaId });
            this.setState({ currentMediaProduct: res.body[0] })
        }
    }

    async onTogglePresenter(e) {
        try {
            const isPresenting = !this.props.screen.isPresenting;
            const res = await superagent.put(`/api/admin/screen/${this.props.screen.id}`).accept('json').send({ isPresenting });
            this.props.onScreenUpdated();
        } catch (e) {
            console.error(e);
        }
    }

    async onToggleMonitor(e) {
        try {
            const isMonitor = !this.props.screen.isMonitor;
            const res = await superagent.put(`/api/admin/screen/${this.props.screen.id}`).accept('json').send({ isMonitor });
            this.props.onScreenUpdated();
        } catch (e) {
            console.error(e);
        }
    }

    async onSetScreenFormat(e, { name, value }) {
        try {
            const res = await superagent.put(`/api/admin/screen/${this.props.screen.id}`).accept('json').send({ format: value });
            this.props.onScreenUpdated();
        } catch (e) {
            console.error(e);
        }
    }

    getEstimatedPosition() {
        if (this.props.screen.sharedMediaSession) {
            const { position, serverTime, startTime } = this.props.screen.sharedMediaSession;
            return (position + ((1000.0 * (serverTime - startTime)) - position));
        }
        throw new Error("Can't do it.");        
    }

    async pauseSharedMediaSession(e) {
        try {
            const position = this.getEstimatedPosition();
            const res = await superagent.put(`/api/admin/screen/${this.props.screen.id}/session`).accept('json').send({ action: "Pause", position  });
            this.props.onScreenUpdated();
        } catch (e) {
            console.error(e);
        }
    }

    async resumeSharedMediaSession(e) {
        try {
            const position = this.getEstimatedPosition();
            const res = await superagent.put(`/api/admin/screen/${this.props.screen.id}/session`).accept('json').send({ action: "Resume", position });
            this.props.onScreenUpdated();
        } catch (e) {
            console.error(e);
        }
    }

    async seekSharedMediaSession(e) {
        try {
            // HACK HACK HACK
            //
            // Without this, the position will reset to 0.
            const position = this.getEstimatedPosition();
            const res = await superagent.put(`/api/admin/screen/${this.props.screen.id}/session`).accept('json').send({ action: "Seek", position: position + 5000 });
            this.props.onScreenUpdated();
        } catch (e) {
            console.error(e);
        }
    }
    
    showDeleteScreenModal(roomIndex, e) {
        this.setState({ isShowingDeleteScreenModal: true});
    }

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

        this.setState({ isShowingDeleteScreenModal: false });

        try {
            const res = await superagent.delete(`/api/admin/screen/${this.props.screen.id}`).accept('json');
            this.props.onScreenUpdated();
        } catch (e) {
            console.error(e);
        }
    }

    closeDeleteScreenModal(e) {
        this.setState({isShowingDeleteScreenModal: false});
    }

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

        const createdAt = formatInTimeZone(new Date(this.props.screen.createdAt), DEFAULT_TIMEZONE, 'PPPp z');
        const fromNow = formatDistanceToNow(new Date(this.props.screen.createdAt), { addSuffix: true });

        const screenTitle = <div><strong>#{this.props.screenIndex + 1} {this.props.screen.name}</strong><Label color="blue">{this.props.screen.screenType}</Label></div>

        return (
            <Segment>
                <Table basic='very' definition={false}>
                    <Table.Body>
                        <Table.Row>
                            <Table.HeaderCell>{screenTitle}</Table.HeaderCell>
                            <Table.Cell textAlign='right'><small>Created: {createdAt} ({fromNow})</small></Table.Cell>
                        </Table.Row>
                    </Table.Body>
                </Table>
                
                <Table compact celled definition>
                    <Table.Body>
                        {(this.props.screen.screenType === "MediaServer") &&
                            <Table.Row>
                                <Table.HeaderCell>Media Server</Table.HeaderCell>
                                <Table.Cell>
                                    <Label color="blue">{this.props.screen.mediaServer.id}</Label>
                                    <Label>{this.props.screen.mediaServer.ipAddress}</Label>
                                    <Label>Load: {this.props.screen.mediaServer.load}%</Label>
                                </Table.Cell>
                            </Table.Row>
                        }

                        {(this.props.screen.screenType === "MediaServer") &&
                            <Table.Row>
                                <Table.HeaderCell width={2}>Controls</Table.HeaderCell>
                                <Table.Cell>
                                    <Radio toggle label='Presenter' checked={this.props.screen.isPresenting} disabled={this.state.loading} onChange={this.onTogglePresenter.bind(this)} /><br />
                                    <Radio toggle label='Monitor' checked={this.props.screen.isMonitor} disabled={this.state.loading} onChange={this.onToggleMonitor.bind(this)} /><br />
                                    Format: <Dropdown
                                        inline
                                        label='Format'
                                        loading={this.state.loading}
                                        size="small"
                                        value={this.props.screen.format}
                                        name="format"
                                        closeOnChange
                                        options={[
                                            {
                                                key: "Regular", text: "Regular", value: "Regular"
                                            },
                                            {
                                                key: "SBS", text: "SBS", value: "SBS"
                                            },
                                            {
                                                key: "OverUnder", text: "OverUnder", value: "OverUnder"
                                            }
                                        ]}
                                        onChange={this.onSetScreenFormat.bind(this)} />
                                </Table.Cell>
                            </Table.Row>
                        }

                        {(this.props.screen.screenType === "ChannelId") &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>Channel</Table.HeaderCell>
                                <Table.Cell href={`/tv/channel/${this.props.screen.channel.id}`}>
                                    <Segment basic>
                                    <Header as='h4'>
                                        <Image src={this.props.screen.channel.texture.url} rounded size='small' verticalAlign='middle' floated='left' />
                                        {this.props.screen.channel.name}<br />
                                        {this.props.screen.channel.description}
                                    </Header>
                                    </Segment>
                                </Table.Cell>
                            </Table.Row>
                        }

                        {(this.props.screen.screenType === "LocalFileId") &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>Local File</Table.HeaderCell>
                                <Table.Cell>
                                    {this.props.screen.sharedMediaSession.localFileId}
                                </Table.Cell>
                            </Table.Row>
                        }

                        {(this.props.screen.screenType === "App") &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>External Url</Table.HeaderCell>
                                <Table.Cell>
                                    {this.props.screen.sharedMediaSession.appUrl}
                                </Table.Cell>
                            </Table.Row>
                        }

                        {(this.props.screen.screenType === "LocalFileId") &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>Playback</Table.HeaderCell>
                                <Table.Cell>
                                    State: <Label>{this.props.screen.sharedMediaSession.state}</Label> Position: {this.props.screen.sharedMediaSession.position} <br />
                                    {this.props.screen.sharedMediaSession.state === "Playing" && <Button size="tiny" onClick={this.pauseSharedMediaSession.bind(this)}><Icon name='pause' />Pause</Button>}
                                    {this.props.screen.sharedMediaSession.state === "Paused" && <Button size="tiny" onClick={this.resumeSharedMediaSession.bind(this)}><Icon name='play' />Resume</Button>}
                                    <Button size="tiny" onClick={this.seekSharedMediaSession.bind(this)}><Icon name='forward' />Forward</Button>
                                </Table.Cell>
                            </Table.Row>
                        }

                        {(this.props.screen.screenType === "BigMediaId") &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>Media Product</Table.HeaderCell>
                                <Table.Cell>
                                    <a href={`/cinema/product/${this.props.screen.mediaProduct.bigMediaId}`}>{this.props.screen.mediaProduct.title}</a>
                                    <Label>{Math.floor(this.props.screen.mediaProduct.duration / 60000 )} mins</Label>
                                    <Label color={this.props.screen.mediaProduct.status === "ACTIVATED" ? "green" : "grey"}>{this.props.screen.mediaProduct.status}</Label>
                                    <Label>({this.props.screen.mediaProduct.entitlementClass})</Label>
                                </Table.Cell>
                            </Table.Row>
                        }

                        {(this.props.screen.screenType === "BigMediaId" || this.props.screen.screenType === "App") &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>Playback</Table.HeaderCell>
                                <Table.Cell>
                                    State: <Label>{this.props.screen.sharedMediaSession.state}</Label> Position: {this.props.screen.sharedMediaSession.position} <br />
                                    {this.props.screen.sharedMediaSession.state === "Playing" && <Button size="tiny" onClick={this.pauseSharedMediaSession.bind(this)}><Icon name='pause' />Pause</Button>}
                                    {this.props.screen.sharedMediaSession.state === "Paused" && <Button size="tiny" onClick={this.resumeSharedMediaSession.bind(this)}><Icon name='play' />Resume</Button>}
                                    <Button size="tiny" onClick={this.seekSharedMediaSession.bind(this)}><Icon name='forward' />Forward</Button>
                                </Table.Cell>
                            </Table.Row>
                        }
                    </Table.Body>
                    <Table.Footer fullWidth>
                        <Table.Row>
                            <Table.HeaderCell colSpan='2'>
                                <Button floated='right' color='red' onClick={this.showDeleteScreenModal.bind(this)}><Icon name='trash' />Delete screen</Button>
                            </Table.HeaderCell>
                        </Table.Row>
                    </Table.Footer>
                </Table>

                <Modal dimmer="inverted" closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                    onClose={this.closeDeleteScreenModal.bind(this)}
                    open={this.state.isShowingDeleteScreenModal}>
                    <Header icon='archive' content='Delete the screen' />
                    <Modal.Content>{
                        <div>
                            <p>Are you sure you want to delete the screen {this.props.screen.screenType} ({this.props.screen.id})?</p>
                            <p><b>People will have nothing to watch!!!</b></p>
                        </div>
                    }
                    </Modal.Content>
                    <Modal.Actions>
                        <Button color='red' onClick={this.onDeleteScreen.bind(this)}>
                            <Icon name='trash' />Yes, Delete this screen
                        </Button>
                    </Modal.Actions>
                </Modal>
            </Segment>
        );
    }
}
