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

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

import MoviesTVWrapper from './MoviesTVWrapper.jsx';

import {
    Container,
    Segment,
    Grid,
    Header,
    Image,
    Icon,
    Button,
    Table,
    Form,
    Label,
    Message,
    Menu,
    Tab,
    Dropdown,
    Modal,
    Card, 
    Divider} from 'semantic-ui-react'

export default class MediaItems extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            currentMediaItems: [],
            originaMediaItems: [],
            searchTerm: ""
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });
        const res = await superagent.get(`/api/admin/media/items`).accept('json');
        this.setState({ originaMediaItems: res.body, currentMediaItems: res.body, loading: false });
    }

    onSearch(e, { name, value }) {
        e.preventDefault();
        if (value.length >= 1) {
            const currentMediaItems = this.state.originaMediaItems.filter(mediaItem => _.toLower(mediaItem.title).includes(_.toLower(value)));
            this.setState({ currentMediaItems });
        } else {
            if (this.state.currentMediaItems.length !== this.state.originaMediaItems.length) {
                this.setState({ currentMediaItems: this.state.originaMediaItems });
            }
        }
    }

    onSorted(clickedColumn) {
        const { currentMediaItems, sortDirection } = this.state;
        const newSortDirection = sortDirection === 'ascending' ? 'descending' : 'ascending';
        const sortedMediaItems = _.sortBy(currentMediaItems, [clickedColumn]);
        if (newSortDirection === "descending") {
            sortedMediaItems.reverse();
        }
        this.setState({
            currentMediaItems: sortedMediaItems,
            sortDirection: newSortDirection
        });
    }

    onClickMediaItem(mediaItem, e) {
        this.props.history.push({pathname: `/cinema/media_item/${mediaItem.id}`});
    }

    render() {
        return (
            <MoviesTVWrapper loading={this.state.loading} title="All Media Items">
                <Form>
                    <Form.Group inline>
                        <Form.Input widths={4} autoComplete="off" icon="search" label='Search' placeholder='Search' 
                            name="search" onChange={this.onSearch.bind(this)} />
                        <Button href={`/cinema/media_item`}>Create a media item</Button>
                    </Form.Group>
                </Form>
                
                <Table compact celled sortable>
                <Table.Header>
                    <Table.Row>
                        <Table.HeaderCell onClick={this.onSorted.bind(this, "title")} width={2}>Title</Table.HeaderCell>
                        <Table.HeaderCell onClick={this.onSorted.bind(this, "type")} width={2}>Type</Table.HeaderCell>
                        <Table.HeaderCell onClick={this.onSorted.bind(this, "cdn")} width={2}>Content Delivery</Table.HeaderCell>
                        <Table.HeaderCell onClick={this.onSorted.bind(this, "isStereo")} width={2}>Rendering</Table.HeaderCell>
                        <Table.HeaderCell onClick={this.onSorted.bind(this, "duration")} width={2}>Duration</Table.HeaderCell>
                        <Table.HeaderCell onClick={this.onSorted.bind(this, "createdAt._seconds")} width={2}>Created At</Table.HeaderCell>
                        <Table.HeaderCell width={1}>Tools</Table.HeaderCell>
                    </Table.Row>
                </Table.Header>
                <Table.Body>

                {this.state.currentMediaItems.map(mediaItem => {
                    let steroLabel = null;
                    let stereoWidth = null;
                    if (mediaItem.isStereo === false) {
                        steroLabel = (<Label>Default (2D)</Label>);
                    } else {
                        if (mediaItem.stereoPacking === "LeftRight") {
                            steroLabel = (<Label color="teal">Stereo 3D (Left/Right)</Label>);
                        } else if (mediaItem.stereoPacking === "OverUnder") {
                            steroLabel = (<Label color="teal">Stereo 3D (Over/Under)</Label>);
                        }
                        stereoWidth =  (<Label>{mediaItem.stereoWidth}</Label>)
                    }

                    const createdAt = formatInTimeZone(fromUnixTime(mediaItem.createdAt._seconds), DEFAULT_TIMEZONE, 'PPPp z');

                    const cdnOriginalFilename = (mediaItem.cdnDataSnapshot && mediaItem.cdnDataSnapshot.original_filename) ? mediaItem.cdnDataSnapshot.original_filename : null;

                    const tempDuration = mediaItem.duration || 0;
                    const hours = Math.floor(tempDuration / 3600000);
                    const minutes = ((tempDuration - (hours * 3600000)) / 60000).toFixed(0);
                    const duration = hours > 0 ? hours + "hr " + minutes + "min" : minutes + "min";

                    let isPositive = (hours === 0);

                    return (
                        <Table.Row positive={isPositive} key={mediaItem.id} style={{cursor: 'pointer'}} onClick={this.onClickMediaItem.bind(this, mediaItem)}>
                            <Table.Cell width={2}>
                                <Header as='h4' image>{mediaItem.title}
                                </Header>
                            </Table.Cell>
                            <Table.Cell width={2}>
                                <Label>{mediaItem.type}</Label>
                            </Table.Cell>
                            <Table.Cell width={2}>
                                <Label color="blue">{mediaItem.cdn}</Label>
                                {mediaItem.cdnId}<br /><small>{cdnOriginalFilename}</small>
                            </Table.Cell>
                            <Table.Cell width={2}>
                                {steroLabel}{stereoWidth}
                            </Table.Cell>
                            <Table.Cell width={2}>
                                <Label>{duration}</Label>
                            </Table.Cell>
                            <Table.Cell width={2}>
                                {createdAt}
                            </Table.Cell>
                            <Table.Cell>
                                <Button href={`/cinema/media_item/${mediaItem.id}`}>Edit</Button>
                            </Table.Cell>
                    </Table.Row>
                );
            })}
                </Table.Body>
            </Table>
            </MoviesTVWrapper>
        );
    }
}
