import React from 'react';
import superagent from 'superagent';
import {Button, Icon} from 'semantic-ui-react';

export default class ToolPathDownloadButton extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false
        };
    }

    async onDownloadToolPath() {
        this.setState({ loading: true });
        try {
            const res = await superagent.get(`/api/admin/fabricator/job/${this.props.job.id}/toolpath`).accept('text/plain');
            const blob = new Blob([res.text], {type: "text/plain"});
            let url = window.URL.createObjectURL(blob);
            let a = document.createElement("a");
            a.href = url;
            a.download = `tool_path_${this.props.job.id}.nc`;
            document.body.appendChild(a);
            a.click();
        } catch (e) {
            console.error(e);
        }
        this.setState({ loading: false });
    }

    render() {
        const AWAITING_MANUFACTURE = 11;
        if (this.props.job && this.props.job.jobState >= AWAITING_MANUFACTURE) {
            return (
                <Button loading={this.state.loading} size="small" onClick={this.onDownloadToolPath.bind(this)}><Icon name='download' />Download (.nc file)</Button>
            );
        } else {
            return null;
        }
    }
}
