import React, { Component } from 'react';
import axios from "axios";
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getUsersByInvestigationIds, getDatasetsById } from '../../api/icat/icatPlus.js'
import Loader from 'react-loader-advanced';
import { doSignIn } from '../../actions/login.js';
import { PERSPECTIVE } from '../../constants/Perspectives.js'
import { Row, Col, Grid, Panel } from 'react-bootstrap';
import { addDatasetById, removeDatasetById } from '../../actions/selection.js';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import DOIForm from '../../components/doi/DOIForm.js';
import _ from 'lodash';


class MintSelectionContainer 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 => {
                let investigationUsers = res.data;
                this.setState({
                    investigationUsers: 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 {
                        let datasets = res.data;
                        this.setState({
                            datasets: datasets,
                            filtered: datasets,
                            fetching: false,
                            fetched: true
                        });

                        this.getUsers(_.uniq(datasets.map(function (o) { return 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();
        }*/

        debugger
        if ((!this.props.user) || (!this.props.user.sessionId)) {
            return null;
        }

        const options = {
            paginationSize: 10,
            sizePerPage: 25,
            paginationShowsTotal: true,
            hidePageListOnlyOnePage: true
        };

        const message = <span>Loading list of authors</span>;

        return <Grid fluid style={{ margin: "60px" }}>
            <Row className="show-grid">
                <Col xs={8}>
                    <Panel bsStyle="primary">
                        <Panel.Heading>
                            <strong>Please fill the next form</strong>
                        </Panel.Heading>
                        <Loader show={this.state.fetching} message={message}>
                            <Panel.Body>
                                <DOIForm investigationUsers={this.state.investigationUsers} sessionId={this.props.user.sessionId} datasets={this.state.datasets} ></DOIForm>
                            </Panel.Body>
                        </Loader>
                    </Panel>
                </Col>
                <Col xs={4}>
                    <Panel bsStyle="primary">
                        <Panel.Heading>
                            <strong>Dataset List</strong>
                        </Panel.Heading>
                        <Panel.Body>
                            <BootstrapTable
                                data={this.state.datasets}
                                options={options}
                                striped
                                hover
                                condensed>
                                <TableHeaderColumn width='10%' hidden isKey dataField='id'>id</TableHeaderColumn>
                                <TableHeaderColumn width='60%' dataFormat={this.nameFormatter} dataField='name'>Name</TableHeaderColumn>
                                <TableHeaderColumn width='20%' dataField='investigationName'>Proposal</TableHeaderColumn>
                                <TableHeaderColumn width='20%' dataField='definition'>Technique</TableHeaderColumn>
                            </BootstrapTable>
                        </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)
    };
}

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

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

