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

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

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

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

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

	render()
	{
		const { template } = this.props;
		const { downloading } = this.state;

		if(template !== undefined && template !== null)
		{
			return (
				<div className="row interactive" onClick={ this._handle_onDownloadFile }>
					<p className="doc_name i-pdf extension" data-format={ template.extension } style={{ flexDirection: "column", display: "flex", alignItems: "flex-start", }}>
						{ template.filename.substring(0, template.filename.lastIndexOf(".")) }
						<span style={{ position: "relative", color: downloading ? "#8e94a780" : "#8e94a7", }}>
							Скачать шаблон{ downloading ? (<SpinnerCircular size={ 20 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" style={{ position: "absolute", right: 0, marginRight: "-26px", top: 0, }} />) : null }
						</span>
					</p>
				</div>
			)
		}

		return null;
	}
}