import React from 'react'
import {connect} from 'react-redux'
import {Link, NavLink} from 'react-router-dom'
import {push} from 'react-router-redux'
import ReactMarkdown from 'react-markdown'
import Moment from 'moment'

import {getEvents} from '../actions.js'
import {
    showEditLink,
    showCreateLink,
    showBookLink,
    showManageLink,
    showApplyToBookLink,
    showBookingEditLink
} from '../permission.js'
import {getUserBookings} from '../../bookings/actions.js' //deep import, bad cause circular..
import {applyToBookEvent, manageEvent} from '../../../shared/permissions.js'

import {
    Button,
    Row,
    Col,
    Card,
    CardBody,
    CardTitle,
    CardSubtitle,
    CardImg
} from 'reactstrap';

//Event listing

class EventList extends React.Component {
    constructor(props) {
        super(props);

        this.clickCreate = this.clickCreate.bind(this);
    }

    clickCreate(e) {
        e.preventDefault();
        dispatch(push('/event/create'));
    }

    render() {
        const user = this.props.User.toJS();
        let events = this.props.Events.toSet().filter(e => manageEvent(user, e.toJS()) || new Date(e.get("startDate")) > new Date()).sort((a, b) => a.get("startDate").localeCompare(b.get("startDate"))).map((e) =>
            <Event
            User={user} {...e.toJS()} key={e.get("id")}/>).toArray();
        return (<React.Fragment>
            <Row>
                <Col>
                    {events}
                </Col>
            </Row>
            <Row>
                <Col>
                    <CreateButton clickCreate={this.clickCreate}/>
                </Col>
            </Row>
        </React.Fragment>);

    }
}

const CreateButton = showCreateLink((props) => <Button color="success" onClick={props.clickCreate}>New
    Event</Button>);


const Event = (props) => {


    const EditLink = showEditLink(() => <NavLink event={props} to={"/event/" + props.id + "/edit"}>Edit</NavLink>);
    const ManageLink = showManageLink(() => <NavLink to={"/event/" + props.id + "/manage"}>Manage</NavLink>);
    const EditApplyButton = getEditApplyButton(props.User, props);

    return (<Card className="mb-3">
        <CardImg top src="/event-header.jpg" alt="Card image cap"/>
        <CardBody>
            <EditApplyButton event={props} booking={props.booking}/>
            <CardTitle>{props.name}</CardTitle>
            <CardSubtitle>{Moment(props.startDate).format('Do')} - {Moment(props.endDate).format('Do MMMM YYYY')}</CardSubtitle>
            <ReactMarkdown escapeHtml={true} source={props.description}/>
            <div className="float-right">
                <EditLink event={props}/>
                {" "}
                <ManageLink event={props}/>
            </div>
        </CardBody>
    </Card>);
};

const getEditApplyButton = (user, event) => {
    if (event.bookingPolicy !== 'guest' && user.id === 1)
        return () => <Link to={"/user"}
                           className="btn btn-primary float-right">Log in to Book</Link>;

    if (event.booking !== undefined) {
        return showBookingEditLink(() => <Link to={"/booking/" + event.booking.id + "/edit"}
                                               className="btn btn-primary float-right">Edit
            My Booking</Link>)
    }
    if (applyToBookEvent(user, event)) {
        return showApplyToBookLink(() => <Link to={"/event/" + event.id + "/apply"}
                                               className="btn btn-primary float-right">Apply to book</Link>);
    }
    if (event.application !== undefined) {
        return () => <button className="btn btn-primary float-right disabled" disabled>Applied</button>;
    }
    return showBookLink(() => <Link to={"/event/" + event.id + "/book"}
                                    className="btn btn-primary float-right">Book</Link>)
};


//Connect to redux

const mapStateToProps = (state) => {

    const User = state.getIn(["User", "user"]);
    const userId = User.get("id");
    let Events = state.getIn(["Events", "events"]);
    const Bookings = state.getIn(["Bookings", "bookings"]);
    Events = Events.map(e => {
        e = e.set("booking", Bookings.find(b => b.get("eventId") === e.get('id') && b.get("userId") === userId));
        return e.set("application", User.get("applications").find(a => a.get('eventId') === e.get('id')));
    });
    return {User, Events};
}


const mapDispatchToProps = {
    getEvents: getEvents,
    getUserBookings: getUserBookings
};

var VisibleEventList = connect(
    mapStateToProps,
    mapDispatchToProps
)(EventList);

export default VisibleEventList;
@@ -1063,16 +1063,340 @@
 events =
+ this.props.Events.toSet()%0A            .filter(e =%3E new Date(e.get(%22startDate%22)) %3E new Date())%0A            .sort((a, b) =%3E a.get(%22startDate%22).localeCompare(b.get(%22startDate%22)))%0A            .map((e) =%3E%0A                %3CEvent User=%7Buser%7D %7B...e.toJS()%7D key=%7Be.get(%22id%22)%7D/%3E)%0A            .toArray();%0A%0A        let previousEvents =
  this.pr
@@ -1458,10 +1458,10 @@
 ()) 
-%7C%7C
+&&
  new
@@ -1478,33 +1478,33 @@
 t(%22startDate%22)) 
-%3E
+%3C
  new Date()).sor
@@ -1499,16 +1499,29 @@
  Date())
+%0A            
 .sort((a
@@ -1580,17 +1580,35 @@
 tDate%22))
-)
+ * -1)%0A            
 .map((e)
@@ -1627,26 +1627,18 @@
     
+    
 %3CEvent
-%0A           
  Use
@@ -1680,16 +1680,29 @@
 id%22)%7D/%3E)
+%0A            
 .toArray
@@ -1701,24 +1701,26 @@
 .toArray();%0A
+%0A%0A
         retu
@@ -1843,32 +1843,376 @@
          %3C/Row%3E%0A
+            %7B previousEvents.length %3E 0 ? %3CReact.Fragment%3E%0A            %3CRow%3E%0A                %3CCol%3E%0A                    %3Ch4%3EPrevious Events%3C/h4%3E%0A                %3C/Col%3E%0A            %3C/Row%3E%0A            %3CRow%3E%0A                %3CCol%3E%0A                    %7BpreviousEvents%7D%0A                %3C/Col%3E%0A            %3C/Row%3E%0A            %3C/React.Fragment%3E : null %7D%0A
             %3CRow

Split out previous events