import React from 'react';
import superagent from 'superagent';
import {Button, Header, Label, Table, Image} from 'semantic-ui-react';

import Entitlement from './Entitlement.jsx';
import MoviesTVWrapper from './MoviesTVWrapper.jsx';
import EntitlementsList from './EntitlementsList.jsx';

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

    async componentDidMount() {
        const res = await superagent.get(`/api/admin/media/entitlements`).accept('json');
        this.setState({ entitlements: res.body});
    }

    async getSalesData() {
        this.setState({ loading: true });
        const res = await superagent.get(`/api/admin/media/entitlements/export`).accept('text/tab-separated-values');
        const blob = new Blob([res.text], {type: "text/tab-separated-values"});
        let url = window.URL.createObjectURL(blob);
        let a = document.createElement("a");
        a.href=url;
        a.download = 'sales_report.tsv';
        document.body.appendChild(a);
        a.click();
        this.setState({ loading: false });
    }

    render() {
        return (
            <MoviesTVWrapper title="Cinema Sales" loading={this.state.loading}>
                <Button onClick={this.getSalesData.bind(this)} >Download Sales Report (.csv)</Button>
                <EntitlementsList entitlements={this.state.entitlements} showAccount={true} />
            </MoviesTVWrapper>
        );
    }
}
