
import React from 'react';

import Notification from '../../../Tools/Notification'

import UploadServices from '../../../Services/UploadServices'

import BaseControl from '../../BaseControl.jsx'


export default class UploaderControl extends BaseControl {

    constructor(props) {
        super(props, "UploaderControl");  

        //state 0 - выбор файла
        //state 1 - загрузка
        this.state = { progress: 0, ButtonUploadEnable: true, _state: 0, FileInfo: {}, ResultMsg: "" };


        this.uploadServices = new UploadServices();
        this.uploadServices.OnProggresseChange = this.OnProgresseChange;
        //this.uploadServices.OnIDReceived = null;
        this.uploadServices.OnError = this.OnError;
    }

    UploadClick() {

        let input = this.refs.file;
        let files = input.files;


        if (files.length == 0)
            return;
        let file = files[0];

        this.setState({ ButtonUploadEnable: false, _state: 1, FileInfo: { name: file.name, size: file.size } });

        this.uploadServices.UploadFileAsync(
            file,
            this.GlobalState.MainExplorer.ID
        ).then(function () {
            Notification.MesOk('Complete','Upload');

            this.setState({ ButtonUploadEnable: true, _state: 0, FileInfo: {}, ResultMsg: "" });
            this.EventRegister.EventAction(this.GlobalState.MainExplorer.ChangeEvent);
            input.value = "";
        }.bind(this));
    }

    CancelClick() {
        this.uploadServices.Cansel();
        this.setState({ ButtonUploadEnable: true, _state: 0, FileInfo: {} });
    }

    OnProgresseChange(Process) {
        this.setState({ progress: Process });
    }

    OnError(Msg) {
        this.setState({ progress: 0, ButtonUploadEnable: true, _state: 0, FileInfo: {}, ResultMsg: Msg });
    }



    render() {
        return (
            <div>
                <h2>Upload</h2>
                <p>
                    <input ref="file" type="file" disabled={!this.state.ButtonUploadEnable} />
                    <button disabled={!this.state.ButtonUploadEnable} onClick={this.UploadClick}>Upload</button>
                    <button disabled={this.state.ButtonUploadEnable} onClick={this.CancelClick}>Cancel</button>
                </p>

                {this.state._state == 1
                    ?
                    <div>
                        <p>Прогресс {this.state.progress} %</p>
                        <p>Выполняется загрука файла:</p>
                        <p>Имя файла: {this.state.FileInfo.name}</p>
                        <p>Размеры файла: {this.state.FileInfo.size}</p>
                    </div>
                    : ""
                }

                {this.state.ResultMsg != ""
                    ? <p>Результат: {this.state.ResultMsg}</p>
                    : null
                }

            </div>
        );
    }
}