import axios from 'axios';
import { uniq } from 'lodash-es';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Col, Grid, Panel, Row } from 'react-bootstrap';
import BootstrapTable2 from 'react-bootstrap-table-next';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { doSignIn } from '../../actions/login';
import { addDatasetById, removeDatasetById } from '../../actions/selection';
import {
  getDatasetsById,
  getUsersByInvestigationIds,
} from '../../api/icat/icatPlus';
import DOIForm from '../../components/doi/DOIForm';
import Loader from '../../components/Loader';
import { PERSPECTIVE } from '../../constants';

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

    this.state = {
      investigationId: this.props.match.params.id,
      username: this.props.user.username,
      sessionId: this.props.user.sessionId,
      datasets: [],
      filtered: [],
      fetching: false,
      fetched: false,
      datasetIds: this.props.selection.datasetIds,
      investigationUsers: [],
    };
  }
  /*
    groupBy = function (xs, key) {
      return xs.reduce(function (rv, x) {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
      }, {});
    };

    parametersToDatasetObject = function (parametersGroupedByInvestigationId) {
      let datasets = {};
      for (var datasetId in parametersGroupedByInvestigationId) {
        for (var index in parametersGroupedByInvestigationId[datasetId]) {
          var param = parametersGroupedByInvestigationId[datasetId][index];
          var key = param[5];
          var value = param[6];
          if (datasets[datasetId] == null) {
            datasets[datasetId] = {};
          }
          datasets[datasetId][key] = value;

          datasets[datasetId]["id"] = param[0];
          datasets[datasetId]["name"] = param[1];
          datasets[datasetId]["startDate"] = param[2];
          datasets[datasetId]["endDate"] = param[3];
          datasets[datasetId]["investigationName"] = param[4];
          datasets[datasetId]["location"] = param[8];
          datasets[datasetId]["investigationId"] = param[9];
        }
      }

      var array = [];
      for (var ds in datasets) {
        array.push(datasets[ds]);
      }
      return array;
    };
  */

  onLogbookButtonClicked() {
    this.setState({
      perspective: PERSPECTIVE.Events,
    });
  }

  componentDidMount() {
    this.retrieveSelectedDatasetsFromDatabase();
  }

  getUsers(investigationIds) {
    this.setState({
      fetching: true,
    });

    axios
      .get(getUsersByInvestigationIds(this.state.sessionId, investigationIds))
      .then((res) => {
        const investigationUsers = res.data;
        this.setState({
          investigationUsers,
          fetching: false,
          fetched: true,
        });
      })
      .catch((error) => {
        console.log(error);
      });
  }
  retrieveSelectedDatasetsFromDatabase() {
    /*if (!this.state.fetching) {
          this.setState({
            fetching: true
          });
        }*/

    if (this.props.selection.datasetIds.length > 0) {
      axios
        .get(
          getDatasetsById(this.state.sessionId, this.props.selection.datasetIds)
        )
        .then((res) => {
          try {
            const datasets = res.data;
            this.setState({
              datasets,
              filtered: datasets,
              fetching: false,
              fetched: true,
            });

            this.getUsers(uniq(datasets.map((o) => o.investigation.id)));
          } catch (error) {
            console.log(error);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    } else {
      this.setState({
        datasets: [],
        filtered: [],
        fetching: false,
      });
    }
  }

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

    return (
      <Grid fluid style={{ margin: 60 }}>
        <Row className="show-grid">
          <Col xs={8}>
            <Panel bsStyle="primary">
              <Panel.Heading>
                <strong>Please fill in this form</strong>
              </Panel.Heading>
              <Panel.Body>
                {this.state.fetching ? (
                  <Loader message="Loading authors..." inPanel />
                ) : (
                  <DOIForm
                    investigationUsers={this.state.investigationUsers}
                    sessionId={this.props.user.sessionId}
                    datasets={this.state.datasets}
                  />
                )}
              </Panel.Body>
            </Panel>
          </Col>
          <Col xs={4}>
            <Panel bsStyle="primary">
              <Panel.Heading>
                <strong>Dataset List</strong>
              </Panel.Heading>
              <Panel.Body>
                <BootstrapTable2
                  keyField="id"
                  data={this.state.datasets}
                  columns={[
                    { dataField: 'id', text: '', hidden: true },
                    { dataField: 'name', text: 'Name' },
                    { dataField: 'investigationName', text: 'Proposal' },
                    { dataField: 'definition', text: 'Technique' },
                  ]}
                  pageOptions={{
                    paginationSize: 10,
                    sizePerPage: 25,
                    showTotal: true,
                    hidePageListOnlyOnePage: true,
                  }}
                  striped
                  condensed
                  noDataIndication="This is no data to display"
                />
              </Panel.Body>
            </Panel>
          </Col>
        </Row>
      </Grid>
    );
  }
}

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

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

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