import React from "react";
import { SpinnerCircular } from 'spinners-react';

import { getFile, getBitrixFile } from "../../../actions";

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

	_handle_onDownloadFile = () => 
	{
		const { id, filename, url, bitrix } = this.props;
		const { downloading } = this.state;

		if(!downloading)
		{
			this.setState({ downloading: true }, () => 
			{
				if(bitrix)
				{
					getBitrixFile({ url, filename })
					.then(() => { this.setState({ downloading: false }); })
					.catch(() => { this.setState({ downloading: false }); });	
				}
				else
				{
					getFile({ id, filename })
					.then(() => { this.setState({ downloading: false }); })
					.catch(() => { this.setState({ downloading: false }); });	
				}
			});
		}
	}

	render() 
	{
		const { id, filename, url, bitrix, title } = this.props;
		const { downloading } = this.state;

		const s = this.props.style !== undefined ? this.props.style : {};
		return (
			<a style={{ ...{ cursor: "pointer", opacity: (bitrix && url === null) || (!bitrix && id === null) ? 0.5 : 1.0 }, ...s }} className={`button button-blue ${ this.props.class !== undefined ? this.props.class : "" }`} onClick={ () => { (bitrix && url === null) || (!bitrix && id === null) ? {} : this._handle_onDownloadFile() }}>
				{ downloading ? (
					<SpinnerCircular size={24} thickness={ 100 } speed={ 100 } color="rgba(255, 255, 255, 1)" secondaryColor="rgba(255, 255, 255, 0.5)" />
				) : title !== undefined ? title : "Скачать" }
			</a>
		)
	}
}