import React from 'react';
import axios from "axios";
import { Label, SplitButton, MenuItem, Panel, Form, FormGroup, ControlLabel, Button, FormControl } from 'react-bootstrap';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { getMintDOI } from '../../api/icat/icatPlus.js'

export class DOIForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            authors: [],
            investigationUsers: [],
            fetching: false,
            fetched: false
        }

        this.onAfterDeleteRow = this.onAfterDeleteRow.bind(this);
        this.addAuthor = this.addAuthor.bind(this);
    }

    /**
     * Add an author to the table
     */
    addAuthor(investigationUser) {
        let authors = this.state.authors;
        if (!investigationUser.fullName) {
            authors.push({
                "name": this.name.value,
                "surname": this.surname.value,
                "id": this.name.value + "_" + this.surname.value
            });
        }
        else {
            let name = investigationUser.fullName.split(" ")[0];
            let surname = investigationUser.fullName.replace(investigationUser.fullName.split(" ")[0], "")
            authors.push({
                "name": name,
                "surname": surname,
                "id": name + "_" + surname
            });
        }
        this.setState({
            authors: authors
        });
    }


    onAfterDeleteRow(rowKeys) {
        let authors = this.state.authors;
        for (var i = 0; i < rowKeys.length; i++) {
            authors = authors.filter(function (o) { return o.id !== rowKeys[i] })

        }
        this.setState({
            authors: authors
        });

    }

    /**
     * This method will get the params from the form and will cal to ICAT+ to mint a new DOI
     */
    mint() {
        let authors = this.state.authors;
        let title = this.title.value;
        let abstract = this.abstract.value;
        let datasetIdList = [];
        for (var i = 0; i < this.props.datasets.length; i++) {
            datasetIdList.push(this.props.datasets[i].id);
        }
        var url = getMintDOI(this.props.sessionId);
        axios.post(url, {
            title: title,
            abstract: abstract,
            datasetIdList: datasetIdList,
            authors: authors
        })
            .then(function (response) {
                if (response) {
                    if (response.data) {
                        if (response.data.message) {
                            alert("Your DOI has been created " + response.data.message);
                        }
                    }
                }
            })
            .catch(function (error) {
                if (error) {
                    if (error.response) {
                        if (error.response.data) {
                            if (error.response.data.message) {
                                alert(error.response.data.message);
                            }
                        }
                    }
                }
            });
    }


    renderButton() {

        return <SplitButton
            bsStyle="default"
            title="Add author"
            style={{ width: '100px' }}
            onClick={this.addAuthor}
        >
            {this.props.investigationUsers.map(function (user, i) {
                var bsStyleRole = "default";
                if (user.role === "Principal investigator") {
                    var bsStyleRole = "primary";
                }
                return <MenuItem style={{ width: '350px' }} eventKey={user} onSelect={this.addAuthor}>
                    <span style={{ marginLeft: 10 }}>{user.fullName} </span>
                    <Label bsStyle='info' style={{ marginLeft: 20 }}>{user.investigationName}</Label>
                    <Label bsStyle={bsStyleRole} style={{ marginLeft: 10 }}>{user.role}</Label>
                </MenuItem>
            }, this)}
            <MenuItem divider />

        </SplitButton>

    }
    render() {
        // If you want to enable deleteRow, you must enable row selection also.
        const selectRowProp = {
            mode: 'checkbox'
        };

        const options = {
            paginationSize: 5,
            sizePerPage: 5,
            paginationShowsTotal: true,
            hidePageListOnlyOnePage: true,
            afterDeleteRow: this.onAfterDeleteRow  // A hook for after droping rows.
        };




        return <Form>
            <FormGroup controlId="formControlsTextarea">
                <ControlLabel>Title <Mandatory></Mandatory></ControlLabel>
                <FormControl inputRef={(ref) => { this.title = ref }} componentClass="textarea" placeholder="" />
            </FormGroup>

            <FormGroup controlId="formControlsTextarea">
                <ControlLabel>Abstract <Mandatory></Mandatory></ControlLabel>
                <FormControl inputRef={(ref) => { this.abstract = ref }} componentClass="textarea" placeholder="" />
            </FormGroup>
            <br />
            <Panel bsStyle="primary">
                <Panel.Heading >
                    <Panel.Title >Authors</Panel.Title>
                </Panel.Heading>

                <Panel.Body>

                    <Form inline>
                        <FormGroup controlId="formInlineName">
                            <ControlLabel>Name</ControlLabel>{' '}
                            <FormControl inputRef={(ref) => { this.name = ref }} type="text" />
                        </FormGroup>{' '}
                        <FormGroup controlId="formInlineEmail" style={{ 'marginLeft': '10px' }}>
                            <ControlLabel>Surname</ControlLabel>{' '}
                            <FormControl inputRef={(ref) => { this.surname = ref }} />
                        </FormGroup>{' '}

                        {this.renderButton()}

                    </Form>

                    <br />
                    <BootstrapTable
                        data={this.state.authors}
                        options={options}
                        striped
                        selectRow={selectRowProp}
                        deleteRow={true}
                        hover
                        condensed>
                        <TableHeaderColumn width='50%' isKey hidden dataField='id'>id</TableHeaderColumn>
                        <TableHeaderColumn width='50%' dataField='name'>Name</TableHeaderColumn>
                        <TableHeaderColumn width='50%' dataField='surname'>Surname</TableHeaderColumn>
                    </BootstrapTable>
                </Panel.Body>

            </Panel>
            <br />
            <Button onClick={this.mint.bind(this)} className='btn btn-primary pull-right'>Mint</Button>


        </Form>


    }
}

class Mandatory extends React.Component {
    render() {
        return (
            <span style={{ color: 'red' }}>*</span>

        );
    }
};

export default DOIForm
