import React from 'react';
import axios from "axios";
import { Glyphicon } from 'react-bootstrap';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import './react-bootstrap-treeview.css';
import { getFilesByDatasetId, getDownloadURLByDatafileId } from '../../api/icat/icatPlus.js';
import { stringifyBytesSize } from "../Helpers.js"

class DatasetFileTree extends React.Component {
    constructor(props) {
        super(props);


        this.downloadFormatter = this.downloadFormatter.bind(this);
        this.state = {
            files: [],
            fetched: false,
            username: this.props.username,
            sessionId: this.props.sessionId,
        }
    }


    getStorageStatus() {
        if (Math.random() >= 0.5) {
            return <kbd style={{ 'backgroundColor': 'green' }}>ONLINE</kbd>;
        }
        return <div><kbd style={{ 'backgroundColor': 'orange' }}>ARCHIVED</kbd></div>;
    }

    getDatasetVolume() {
        return <kbd style={{ 'backgroundColor': 'blue' }}>{Math.floor((Math.random() * 100) + 1)} GB</kbd>;
    }


    componentDidMount() {
        axios.get(getFilesByDatasetId(this.props.sessionId, this.props.dataset.id))
            .then(res => {

                this.setState({
                    files: res.data.map(row => row.Datafile),
                    fetching: true
                });
            })
            .catch((error) => {

                if (error.response) {
                    if (error.response.status === 403) {

                    }
                }
            });
    }

    downloadFormatter(row, dataFile) {
        var url = getDownloadURLByDatafileId(this.props.sessionId, dataFile.id);
        return <a href={url}><span><Glyphicon glyph="glyphicon glyphicon-download-alt" /> Download</span></a>
    }

    sizeFormatter(size) {
        return stringifyBytesSize(size);
    }

    render() {
        const options = {
            paginationSize: 20,
            sizePerPage: 20,
            paginationShowsTotal: true,
            hidePageListOnlyOnePage: true
        };


        return (
            <div style={{ marginTop: '20px' }}>
                <BootstrapTable
                    data={this.state.files}
                    options={options}
                    pagination
                    striped
                    search
                    hover
                    condensed>
                    <TableHeaderColumn width='10%' hidden isKey dataField='id'>id</TableHeaderColumn>
                    <TableHeaderColumn width='10%' dataFormat={this.downloadFormatter} dataField='id' >Download</TableHeaderColumn>
                    <TableHeaderColumn width='80%' dataField='name' >location</TableHeaderColumn>
                    <TableHeaderColumn width='10%' dataFormat={this.sizeFormatter} dataField='fileSize' >Size</TableHeaderColumn>

                </BootstrapTable>
            </div>
        );
    }
}

export default DatasetFileTree;