import axios from 'axios';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import {
  Button,
  ButtonToolbar,
  Glyphicon,
  OverlayTrigger,
  Tooltip,
} from 'react-bootstrap';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { setBreadCrumbs } from '../../actions/breadcrumbs';
import { doSignIn, doLogOut } from '../../actions/login';
import { addDatasetById, removeDatasetById } from '../../actions/selection';
import { getDatasetsById } from '../../api/icat/icatPlus';
import DatasetTable from '../../components/Dataset/DatasetTable';
import Loader from '../../components/Loader';
import { PERSPECTIVE } from '../../constants';

class SelectionPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      investigationId: this.props.investigationId,
      username: this.props.user.username,
      sessionId: this.props.user.sessionId,
      datasets: [],
      filtered: [],
      fetching: true,
      datasetIds: this.props.selection.datasetIds,
    };
  }

  componentDidMount() {
    this.retrieveSelectedDatasetsFromDatabase();
    this.props.setBreadCrumbs([{ name: 'Selection' }]);
  }

  retrieveSelectedDatasetsFromDatabase() {
    if (this.props.selection.datasetIds.length > 0) {
      axios
        .get(
          getDatasetsById(this.state.sessionId, this.props.selection.datasetIds)
        )
        .then((res) => {
          this.setState({
            datasets: res.data,
            filtered: res.data,
            fetching: false,
          });
        })
        .catch((error) => {
          if (error.response) {
            if (error.response.status === 401) {
              //this.props.doSignIn();
            }
          }
        });
    } else {
      this.setState({
        datasets: [],
        filtered: [],
        fetching: false,
      });
    }
  }
  render() {
    if (this.props.user.sessionId == null) {
      return null;
    }
    /** This means that datasets has not been loaded yet. It could be done with FETCHING (?) **/

    /*if (this.props.selection.datasetIds.length !== this.state.datasets.length) {
      this.retrieveSelectedDatasetsFromDatabase();
    }*/

    const tooltip = (text) => <Tooltip id="tooltip">{text}</Tooltip>;

    return (
      <div>
        <ButtonToolbar
          className="navbar-fixed-top"
          style={{ backgroundColor: 'white', marginBottom: 10, marginTop: 100 }}
        >
          <div style={{ marginLeft: 40, marginTop: 10 }}>
            <OverlayTrigger
              placement="bottom"
              overlay={tooltip('Mint a DOI for all selected datasets')}
            >
              <Button bsSize="small" bsStyle="primary" href="selection/mint">
                <Glyphicon glyph="plus" /> Mint a DOI
              </Button>
            </OverlayTrigger>
            <OverlayTrigger
              placement="bottom"
              overlay={tooltip('Download all selected datasets')}
            >
              <Button
                style={{ marginLeft: 5 }}
                bsSize="small"
                bsStyle="primary"
                target="_blank"
              >
                <Glyphicon glyph="download" style={{ marginRight: 3 }} />{' '}
                Download all
              </Button>
            </OverlayTrigger>
          </div>
        </ButtonToolbar>

        <div style={{ marginTop: 60 }}>
          {this.state.fetching ? (
            <Loader message="Loading datasets..." />
          ) : (
            <DatasetTable
              selection={this.props.selection}
              removeDatasetById={this.props.removeDatasetById}
              addDatasetById={this.props.addDatasetById}
              sessionId={this.props.user.sessionId}
              datasets={this.state.filtered}
            />
          )}
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.user,
    events: state.events,
    selection: state.selection,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    removeDatasetById: bindActionCreators(removeDatasetById, dispatch),
    addDatasetById: bindActionCreators(addDatasetById, dispatch),
    doSignIn: bindActionCreators(doSignIn, dispatch),
    doLogOut: bindActionCreators(doLogOut, dispatch),
    setBreadCrumbs: bindActionCreators(setBreadCrumbs, dispatch),
  };
}

SelectionPage.propTypes = {
  perspective: PropTypes.oneOf([
    PERSPECTIVE.Datasets,
    PERSPECTIVE.Files,
    PERSPECTIVE.Events,
  ]),
};

export default connect(mapStateToProps, mapDispatchToProps)(SelectionPage);
