import React from 'react';
import { Well, Navbar, Nav, NavItem, MenuItem, Radio, NavDropdown, Checkbox } from 'react-bootstrap';
import EventListMenuButton from './EventListMenuButton';
import { getPDF } from '../../../api/icat/icatPlus';
import { ComboSearch } from 'react-combo-search';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { DOC_VIEW, LIST_VIEW, SORT_EVENTS_FROM_YOUNGEST, SORT_EVENTS_FROM_OLDEST, NEW_EVENT_VISIBLE } from '../../../constants/EventTypes';
import NewlyAvailableEventsDialogue from './NewlyAvailableEventsDialogue';

// styles 
require('./react-datetime.css');
require('./react-combo-select.css');
require('./react-combo-search.css');
require('./eventListMenu.css');
/**
 * The menu displayed above the event list
 */
class EventListMenu extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isNavbarExpanded: false
        };

        this.getSelectPickerData = this.getSelectPickerData.bind(this);
        this.onSelectNavbar = this.onSelectNavbar.bind(this);
        this.onToggleNavbar = this.onToggleNavbar.bind(this);
        this.onSearch = this.onSearch.bind(this);
        this.sortByDate = this.sortByDate.bind(this);
    }

    render() {
        const { investigationId,
            isNewEventVisible,
            numberOfMatchingEventsFound,
            selectionFilter,
            sessionId,
            setNewEventVisibility,
            setView,
            sortingFilter,
            view } = this.props;

        function getCurrentlyPressedSortButton() {
            if (sortingFilter && sortingFilter.createdAt) {
                return sortingFilter.createdAt;
            }
        }
        return (
            <Navbar
                fluid
                expanded={this.state.isNavbarExpanded}
                onSelect={this.onSelectNavbar}
                onToggle={this.onToggleNavbar}
                style={{ background: 'none', border: 'none', WebkitBoxShadow: 'none', boxShadow: 'none', position: 'sticky', top: '0px', backgroundColor: 'white' }}>

                <Navbar.Header>
                    <Navbar.Toggle />
                    <Nav style={{ marginLeft: '0px' }}>
                        <NavItem eventKey={1} href="#" className="logbookNavItem" onClick={() => setNewEventVisibility(NEW_EVENT_VISIBLE)}>
                            <EventListMenuButton text='New' glyph='plus' tooltipText='Create a new event' isEnabled={!isNewEventVisible} />
                        </NavItem>

                        <NavItem eventKey={2} href={'/investigation/' + this.props.investigationId + '/camera'} target='_blank' className="logbookNavItem" >
                            <EventListMenuButton text='Take a photo' glyph='camera' tooltipText='Take a photo' isEnabled={true} />
                        </NavItem>
                    </Nav>
                </Navbar.Header>

                <Navbar.Collapse>
                    <Nav>
                        <NavDropdown eventKey={3} title={<div className='btn btn-sm btn-primary'> View  <span className='caret'></span></div>} id="nav-dropdown" className="logbookNavItem">
                            <MenuItem eventKey={3.1} onSelect={() => setView(DOC_VIEW)} > {view === DOC_VIEW ? <Radio checked readOnly> Classic (user's commented logs)</Radio> : <Radio checked={false} readOnly> Classic (user's commented logs)</Radio>} </MenuItem>
                            <MenuItem eventKey={3.2} onSelect={() => setView(LIST_VIEW)} > {view === LIST_VIEW ? <Radio checked readOnly> Full (all logs)</Radio> : <Radio checked={false} readOnly> Full (all logs)</Radio>} </MenuItem>
                            <MenuItem divider />
                            <MenuItem eventKey={3.3} onSelect={() => this.sortByDate(SORT_EVENTS_FROM_OLDEST)} > {getCurrentlyPressedSortButton() === SORT_EVENTS_FROM_OLDEST ? <Radio checked readOnly> Oldest log on top</Radio> : <Radio checked={false} readOnly> Oldest log on top</Radio>} </MenuItem>
                            <MenuItem eventKey={3.4} onSelect={() => this.sortByDate(SORT_EVENTS_FROM_YOUNGEST)} > {getCurrentlyPressedSortButton() === SORT_EVENTS_FROM_YOUNGEST ? <Radio checked readOnly> Latest log on top</Radio> : <Radio checked={false} readOnly> Latest log on top</Radio>} </MenuItem>
                            <MenuItem divider />
                            <MenuItem eventKey={3.5} onSelect={() => this.props.setEventListAutorefresh(!this.props.isEventListAutorefreshEnabled)}>
                                <Checkbox checked={this.props.isEventListAutorefreshEnabled} readOnly > Refresh logs automatically</Checkbox>
                            </MenuItem>
                        </NavDropdown>
                        <NavItem eventKey={4} href={getPDF(sessionId, investigationId, selectionFilter)} target='_blank' className="logbookNavItem" >
                            <EventListMenuButton text='PDF' glyph='download' tooltipText='Download as PDF' isEnabled={!(isNewEventVisible === undefined || isNewEventVisible === true || numberOfMatchingEventsFound === 0)} />
                        </NavItem>
                        <NavItem eventKey={5} className="logbookNavItem">
                            <NewlyAvailableEventsDialogue isEventListAutorefreshEnabled={this.props.isEventListAutorefreshEnabled} latestEvents={this.props.periodicdata} eventCountSinceLastRefresh={this.props.eventCountSinceLastRefresh} onIconClicked={this.props.getEvents} />
                        </NavItem>
                    </Nav>

                    <Nav pullRight>
                        <NavItem eventKey={6} href="#" className="logbookNavItem">
                            <div className='comboSearchContainer'>
                                <ComboSearch
                                    onSearch={this.onSearch}
                                    selectData={[
                                        { value: 'Everywhere', text: 'Everywhere' },
                                        { value: 'Content', text: 'Content' },
                                        { value: 'Title', text: 'Title' },
                                        { value: 'category', text: 'Category' },
                                        { value: 'Author', text: 'Author' },
                                        { value: 'Tag', text: 'Tag' },
                                        { value: 'Creation date', text: 'Creation date' }
                                    ]}
                                    datePickerCriteria='Creation date'
                                    selectPickerData={this.getSelectPickerData()}
                                />
                            </div>
                            <Well style={{ display: 'inline-block', padding: '4px', marginBottom: '0px', borderTopLeftRadius: '0px', borderBottomLeftRadius: '0px', color: '#666666' }}>
                                <b> &nbsp; {numberOfMatchingEventsFound} found </b>
                            </Well>
                        </NavItem>
                    </Nav>
                </Navbar.Collapse>
            </Navbar>
        );
    }

    getSelectPickerData() {
        let selectPickerData = { category: ['Info', 'Error', 'Command', 'Comment', 'Debug'] };

        if (this.props.availableTags) {
            selectPickerData['Tag'] = this.props.availableTags.map((tag) => ({ value: tag._id, text: tag.name }));
        }

        return selectPickerData;
    }
    /** 
     * Callback triggered when the user clicks the button to expand the navbar in mobile layout 
    */
    onToggleNavbar() {
        this.setState({ isNavbarExpanded: !this.state.isNavbarExpanded });
    }

    /**
     * Callback triggered when the user clicks an element of the navbar.
     * @param {*} eventKey key of the element
     */
    onSelectNavbar(eventKey) {
        if (eventKey != 6) {
            this.onToggleNavbar();
        }
    }

    onSearch(data) {
        return this.props.searchEvents(data);
    }

    sortByDate(sortingOrder) {
        if (sortingOrder && this.props.sortingFilter.createdAt !== sortingOrder) {
            //this.setState({ sortingOrder: sortingOrder })
            this.props.reverseEventsSortingByCreationDate();
        }
    }
}

EventListMenu.propTypes = {
    /** the identifier of the current investigation */
    investigationId: PropTypes.string,
    /** True when the user is writing a new event */
    isNewEventVisible: PropTypes.bool,
    /** the number of events found */
    numberOfMatchingEventsFound: PropTypes.number,
    /** callback function which reverse the sorting of events by date */
    reverseEventsSortingByCreationDate: PropTypes.func.isRequired,
    /** Callback function which reloads the events based on search criteria*/
    searchEvents: PropTypes.func,
    /** selection filter for mongo request */
    selectionFilter: PropTypes.object,
    /* the sessionId*/
    sessionId: PropTypes.string.isRequired,
    /** Callback function triggered when the user clicks on the new event button */
    setNewEventVisibility: PropTypes.func,
    /** the callback function executed when the user clicks the view buttons */
    setView: PropTypes.func,
    /** the filter used to sort event */
    sortingFilter: PropTypes.object.isRequired
};

export default EventListMenu;