import React from 'react';
import superagent from 'superagent';
import constants from '../CloudApi/Constants.js';

import MoviesTVWrapper from './MoviesTVWrapper.jsx';

import {
    Accordion,
    Segment,
    Dropdown,
    Grid,
    Header,
    Form,
    Image,
    Message,
    Icon,
    Button,
    Table,
    Divider} from 'semantic-ui-react'

export default class MediaItemEditor extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            mediaItem: {
                title: "",
                type: "MOVIE",
                locationCodes: ["us"],
                isStereo: false,
                stereoPacking: "Off",
                stereoWidth: "Full"
            },
            cdnInfo: null
        };

        let cdns = [
            "Brightcove_v1", "Youtube", "PlutoTV", "BigscreenTestDRM"
        ];

        this.cdns = cdns.map(cdn => { return {"key": cdn, "value": cdn, "text": cdn}});
    }

    async componentDidMount() {
        if (this.props.match.params.mediaItemId) {
            this.setState({ loading: true });
            const res = await superagent.get(`/api/admin/media/item/${this.props.match.params.mediaItemId}`).accept('json');
            this.setState({ mediaItem: res.body, loading: false });

            await this.loadCDNData();
        }
    }

    async loadCDNData() {
        if (this.state.mediaItem.cdn && this.state.mediaItem.cdnId) {
            this.setState({ cdnInfo: null, loading: true });
            try {
                const res = await superagent.get(`/api/admin/media/cdn/${this.state.mediaItem.cdn}/${this.state.mediaItem.cdnId}`).accept('json');
                this.setState({ cdnInfo: res.body, loading: false });
            } catch (e) {
                console.log(e);
                this.setState({ loading: false });
            }
        }
    }

    async onSaveMediaItem() {
        this.setState({ loading: true });
        if (this.state.mediaItem.id) {
            const res = await superagent.put(`/api/admin/media/item`).send(this.state.mediaItem);
            this.setState({ loading: false });
        } else {
            const res = await superagent.post(`/api/admin/media/item`).send(this.state.mediaItem);
            this.setState({ mediaItem: res.body, loading: false });
        }
    }

    async onCDNInfoChanged(e, { name, value }) {
        const mediaItem = this.state.mediaItem;
        mediaItem[name] = value;
        this.setState({ mediaItem });

        await this.loadCDNData();
    }

    async onChange(e, { name, value }) {
        const mediaItem = this.state.mediaItem;
        mediaItem[name] = value;
        this.setState({ mediaItem });
    }

    render() {
        if (!this.state.mediaItem) {
            return <div />;
        }

        // (<Form.Select required label="CDN Identifier" size="small" name="cdnId"
        // value={this.state.mediaItem.cdnId}
        // options={constants.RoomSizes}
        // onChange={this.onChange.bind(this)} />)

        let onStereoChanged = function(e, { name, value }) {
            if (value === 0) {
                this.state.mediaItem.isStereo = false;
                this.state.mediaItem.stereoPacking = "None";
            } else if (value === 1) {
                this.state.mediaItem.isStereo = true;
                this.state.mediaItem.stereoPacking = "LeftRight";
            } else if (value === 2) {
                this.state.mediaItem.isStereo = true;
                this.state.mediaItem.stereoPacking = "OverUnder";
            }
            this.setState({ mediaItem: this.state.mediaItem });
        }

        // <ReactPlayer url={this.state.mediaItem.uri} playing controls muted />

        const renderSettings = (
            <Table celled striped>
                <Table.Body>
                    <Table.Row>
                        <Table.Cell width={9} verticalAlign="top">
                            <Form.Group inline>
                                <label>Stereo</label>
                                <Form.Radio label='Default (2D)' value={0} checked={this.state.mediaItem.isStereo === false} onChange={onStereoChanged.bind(this)} />
                                <Form.Radio label='Stereo 3D (Left/Right)' value={1} checked={this.state.mediaItem.isStereo === true && this.state.mediaItem.stereoPacking === "LeftRight"} onChange={onStereoChanged.bind(this)} />
                                <Form.Radio label='Stereo 3D (Over/Under)' value={2} checked={this.state.mediaItem.isStereo === true && this.state.mediaItem.stereoPacking === "OverUnder"} onChange={onStereoChanged.bind(this)} />
                            </Form.Group>
                            <Form.Group inline widths="equal">
                                <label>Stereo width</label>
                                <Form.Select required size="small" name="stereoWidth" value={this.state.mediaItem.stereoWidth} options={constants.StereoWidths} onChange={this.onChange.bind(this)} />
                            </Form.Group>
                        </Table.Cell>
                        <Table.Cell width={6} verticalAlign="top">

                        </Table.Cell>
                    </Table.Row>
                </Table.Body>
            </Table>
        )

        let cdnInfo = ( <div /> )
        if (this.state.cdnInfo && this.state.cdnInfo.brightcove) {
            const brightcove = this.state.cdnInfo.brightcove;
            cdnInfo = (
                <Segment>
                    <Header as="h3">CDN Data</Header>
                    <p><Image src={brightcove.images.thumbnail.src} /></p>
                    <p><strong>Created At: </strong> {brightcove.created_at}</p>
                    <p><strong>Name: </strong> {brightcove.name}</p>
                    <p><strong>State: </strong> {brightcove.state}</p>
                    <p><strong>Duration: </strong> {brightcove.duration ? (brightcove.duration / 1000.0) : 0} seconds</p>
                    <p><strong>Original Filename: </strong> {brightcove.original_filename}</p>
                </Segment>
            )
        } else if (this.state.cdnInfo && this.state.cdnInfo.bigscreen) {
            const bigscreen = this.state.cdnInfo.bigscreen;
            cdnInfo = (
                <Segment>
                    <Header as="h3">CDN Data</Header>
                    <p><strong>Name: </strong> {bigscreen.name}</p>
                </Segment>
            )
        }

        if (this.state.mediaItem) {
            return (
                <MoviesTVWrapper loading={this.state.loading}>
                    {(!this.state.mediaItem.id) && <Header as="h2">Create Media Item</Header>}
                    {(this.state.mediaItem.id) && <Header as="h2">Edit Media Item</Header>}

                    <Form size='small' onSubmit={this.onSaveMediaItem.bind(this)}>
                        {(this.state.mediaItem.id) &&
                        <Form.Group>
                            <Form.Input required label='id' value={this.state.mediaItem.id} name="id" readOnly />
                        </Form.Group>}

                        <Form.Group widths="equal">
                            <Form.Input required label='Title' value={this.state.mediaItem.title} name="title" onChange={this.onChange.bind(this)} />
                        </Form.Group>

                        <Form.Group>
                            <Form.Select required label='Type' size="small" name="type" value={this.state.mediaItem.type} options={constants.MediaItemTypes} onChange={this.onChange.bind(this)} />
                        </Form.Group>

                        <div>
                            <Header as="h2">CDN Settings</Header>

                            <Form.Group widths="equal">
                                <Form.Select required label="CDN" size="small" name="cdn"
                                value={this.state.mediaItem.cdn}
                                options={this.cdns}
                                onChange={this.onCDNInfoChanged.bind(this)} />

                                <Form.Input required label="CDN Id" name="cdnId" value={this.state.mediaItem.cdnId} onChange={this.onCDNInfoChanged.bind(this)} />
                            </Form.Group>
                            {cdnInfo}
                        </div>

                        <Header as="h2">Render Settings</Header>

                        {renderSettings}

                        <Segment basic>
                            {(!this.state.mediaItem.id) && <Form.Group><Button primary content='Create media item' type='submit' /></Form.Group>}
                            {(this.state.mediaItem.id) && <Form.Group><Button primary content='Save media item' type='submit' /></Form.Group>}
                        </Segment>
                    </Form>
                </MoviesTVWrapper>
            )
        } else {
            return <div />;
        }
    }
}
