import axios from 'axios';
import React from 'react';
import { Glyphicon } from 'react-bootstrap';
import {
  getDownloadURLByDatafileId,
  getFilesByDatasetId,
} from '../../api/icat/icatPlus';
import { stringifyBytesSize } from '../../helpers';
import ResponsiveTable from '../Table/ResponsiveTable';

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,
        });
      });
  }

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

  render() {
    return (
      <div style={{ marginTop: 20 }}>
        <ResponsiveTable
          data={this.state.files}
          columns={[
            { dataField: 'id', text: '', hidden: true },
            {
              dataField: 'download',
              text: 'Download',
              formatter: this.downloadFormatter,
              headerStyle: { width: '10%' },
            },
            { dataField: 'name', text: 'Location' },
            {
              dataField: 'fileSize',
              text: 'Size',
              formatter: stringifyBytesSize,
              headerStyle: { width: '10%' },
            },
          ]}
          pageOptions={{
            paginationSize: 20,
            sizePerPage: 20,
            showTotal: true,
            hidePageListOnlyOnePage: true,
          }}
        />
      </div>
    );
  }
}

export default DatasetFileTree;
