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


class SelectionContainer 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', link: '/selection' }, { name: 'Datasets'}]);
  }

  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();
    }*/

    return <div>
      <SelectionContainerMenu></SelectionContainerMenu>
      <div style={{ marginTop: "60px" }}>
        <DatasetTable
          selection={this.props.selection}
          removeDatasetById={this.props.removeDatasetById}
          addDatasetById={this.props.addDatasetById}
          sessionId={this.props.user.sessionId}
          datasets={this.state.filtered}
          fetching={this.state.fetching}>
        </DatasetTable>
      </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(doSignIn, dispatch),
    setBreadCrumbs: bindActionCreators(setBreadCrumbs, dispatch)
  };
}

SelectionContainer.propTypes = {
  perspective: PropTypes.oneOf([PERSPECTIVE.DATASETS, PERSPECTIVE.FILES, PERSPECTIVE.EVENTS])
}

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

class SelectionContainerMenu extends React.Component {
  handleKeyPress(event) {
    if (event.key === 'Enter') {
      this.onSearch(event.target.value);
    }
  }

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

    return <div >
      <ButtonToolbar fluid className="navbar-fixed-top" style={{ backgroundColor: 'white', marginBottom: "10px", marginTop: "100px" }}>
        <div style={{ marginLeft: '40px', marginTop: '10px' }}>
          <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: '5px' }} bsSize="small" bsStyle="primary" target="_blank">
              <Glyphicon glyph="download" style={{ marginRight: "3px" }} /> Download all
                          </Button>
          </OverlayTrigger>
        </div>
      </ButtonToolbar>
    </div>
  }

}

