import React from 'react';
import superagent from 'superagent';

import EntitlementsList from '../../MoviesTV/EntitlementsList.jsx';

import { Segment, Header, Button, Form, Divider, Dropdown } from 'semantic-ui-react'

export default class AccountEntitlements extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            entitlements: [],
        };
    }

    async componentDidMount() {
        return Promise.all([
            this.reloadEntitlements(), this.reloadMediaProducts()
        ]);
    }

    async reloadEntitlements() {
        this.setState({loading: true});
        try {
            const entitlementsRes = await superagent.post(`/api/admin/media/entitlements/query`).accept('json').send({
                bigscreenAccountId: this.props.account.id
            });
            this.setState({ entitlements: entitlementsRes.body });
        } catch (e) {
            console.log(e);
        }
        this.setState({loading: false});
    }

    async reloadMediaProducts() {
        this.setState({loading: true});
        try {
            const mediaProductRes = await superagent.get(`/api/admin/media/products`).accept('json');
            const mediaProductOptions = mediaProductRes.body.map(mediaProduct => {
                // Use unityPosterTexture because it is a smaller image.
                return {
                    "key": mediaProduct.id,
                    "value": mediaProduct.bigMediaId,
                    "text": `(${mediaProduct.entitlementClass}) ${mediaProduct.title}`,
                    "image": { src: mediaProduct.marketingData["en-US"].unityPosterTexture && mediaProduct.marketingData["en-US"].unityPosterTexture["src"] }
                }
            });
            this.setState({ mediaProductOptions });
        } catch (e) {
            console.log(e);
        }
        this.setState({loading: false});
    }

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

        if(this.state.selectedBigMediaId){
            this.setState({loading:true});

            try {
                await superagent.post(`/api/admin/media/entitlement`).accept('json').send({
                    bigscreenAccountId: this.props.account.id,
                    bigMediaId: this.state.selectedBigMediaId
                });
                return this.reloadEntitlements();
            } catch (e) {
                console.log(e);
            }
            this.setState({loading: false});
        }
    }

    render() {
        if (this.props.account) {
            let onProductSelectionChanged = async (e, { name, value }) => {
                this.setState({selectedBigMediaId: value});
            };

            return (
                <div>   
                    <Header as="h2">Grant Free Entitlements</Header>
                    <Segment secondary loading={this.state.loading}>
                        <Form.Group>
                            <Dropdown search selection
                                placeholder="Type a media product name or choose an option..."
                                fluid
                                icon='search'
                                loading={this.state.mediaProductOptions === null}
                                size="small"
                                value={this.state.selectedBigMediaId}
                                name="mediaItemId"
                                closeOnChange
                                options={this.state.mediaProductOptions}
                                onChange={onProductSelectionChanged.bind(this)} />
                            <Button onClick={this.onGrantFreeEntitlement.bind(this)}>Grant MediaProduct for Free</Button>
                        </Form.Group>
                    </Segment>

                    <Divider />

                    {(this.state.entitlements && this.state.entitlements.length > 0) && <div>
                        <Divider />
                        <Header as="h2">Purchases ({this.state.entitlements.length})</Header>
                        <EntitlementsList entitlements={this.state.entitlements} showAccount={false} />
                    </div> }
                </div>
            );
        }
    }
}
