import React from 'react';
import PropTypes from 'prop-types'
import _ from 'lodash'
import Moment from 'moment'
import { Table, OverlayTrigger, Tooltip, Glyphicon, Button, Label } from 'react-bootstrap'
import { getContent, convertImagesToThumbnails, getPreviousVersionNumber } from '../../../helpers/EventHelpers';
import { getOriginalEvent } from '../../../helpers/EventHelpers'
import EventIcon from './EventIcon.js';
import LazyLoad from 'react-lazyload';
import { EVENT_CATEGORY_COMMANDLINE, NOTIFICATION } from '../../../constants/EventTypes.js';
import TagListInLine from '../Tag/TagListInLine';
require("./eventList.css");

/**
 * The list of the all events
 */
class EventList extends React.Component {
    collapse(items) {
        let collapsed = [];
        for (let i = 0; i < items.length; i++) {
            const event = items[i];
            if (event.category === EVENT_CATEGORY_COMMANDLINE && !event.previousVersionEvent) {
                let lastEvent = collapsed[collapsed.length - 1];
                if (lastEvent.category === EVENT_CATEGORY_COMMANDLINE) {
                    if (!lastEvent.events) {
                        lastEvent.events = [event];
                    } else {
                        lastEvent.events.push(event);
                    }
                    continue;
                }
            }
            collapsed.push(event);
        }
        return collapsed;
    }

    /** Returns the list of items to be displayed in the table: events + days */
    getItems() {
        let eventsCopy = _.cloneDeep(this.props.events);
        let items = [];
        let lastDate = null; // format DDMMYYYY
        for (let i = 0; i < eventsCopy.length; i++) {
            let date = Moment(getOriginalEvent(eventsCopy[i]).creationDate).format("MMMM Do YYYY");
            if (date !== lastDate) {
                lastDate = date;
                items.push({ text: date, type: "date", anchor: date });
            }
            items.push(eventsCopy[i]);
        }
        return this.collapse(items);
    }

    render() {
        if (!this.props.events || this.props.events.length === 0) {
            return null;
        }

        return <Table responsive style={{ fontSize: '12px' }} >
            <tbody>
                {this.getItems().map((event, index) => {
                    if (event.type === "date") {
                        return <tr key={index}><td style={{ borderTop: '1px solid #f2f2f2', textAlign: 'center', fontSize: '18px', fontWeight: 'bold' }} colSpan={5} ><a name={event.anchor}></a>  {event.text}</td></tr>;
                    }
                    return <Event key={index} availableTags={this.props.availableTags} event={event} onEventClicked={this.props.onEventClicked} ></Event>
                })}
            </tbody>
        </Table>
    }
}

EventList.propTypes = {
    /** the array of unsorted events as provided by the ICAT+ server */
    events: PropTypes.array.isRequired,
    /** Callback function triggered when the user clicks the edit icon */
    onEventCliked: PropTypes.func
}

export default EventList;

class Event extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            collapsed: true
        }
        this.handleClick = this.handleClick.bind(this);
        this.getTags = this.getTags.bind(this);
    }

    handleClick(e) {
        this.setState({ collapsed: !this.state.collapsed });
    }

    getUncollapsedEvents() {
        return (<tbody> {this.props.event.events.map((event, index) => {
            return this.getEventContentBody(event);
        })}</tbody>);
    }

    /**
     * Get the corresponding tags objects for that event
     */
    getTags(event) {


        let eventTags = [];
        if (event && event.tag && event.tag.length !== 0) {
            event.tag.forEach(tagId => {
                let tag = _.find(this.props.availableTags, (availableTag) => _.isEqual(availableTag._id, tagId))
                if (tag) { eventTags.push(tag); };
            });
            return eventTags;
        }
        return null;
    }

    render() {
        let events = [this.props.event];
        if (this.props.event.events && !this.state.collapsed) {
            events = events.concat(this.props.event.events);
        };
        return events.map((event, index) => {
            return <tr key={index} id='contentDocList'>
                <td style={{ width: '16px', borderTop: '0' }}>
                    <EventIcon event={event} />
                </td>
                <td style={{ width: '16px', borderTop: '0', borderRight: '1px solid #f2f2f2' }}>
                    <OverlayTrigger placement="right" overlay={<Tooltip id="tooltip"> <p> Events created on {Moment(getOriginalEvent(event).creationDate).format("MMMM Do YYYY, h:mm:ss a")} </p> </Tooltip>}>
                        <span style={{ cursor: 'pointer', color: '#999999', margin: '0px' }}>{Moment(getOriginalEvent(event).creationDate).format("HH:mm:ss")} </span>
                    </OverlayTrigger>
                </td>
                <td style={{ border: 0 }}>
                    <LazyContentEvent event={event} />
                    {event.events && this.state.collapsed ? <Label style={{ color: "blue", backgroundColor: "white", cursor: "pointer" }} onClick={this.handleClick}  >.... {event.events.length} command lines more</Label> : null}
                </td>
                <td style={{ width: '200px', border: 0 }}>
                    <TagListInLine tags={this.getTags(event)} />
                </td>
                <td style={{ width: '50px', border: 0 }}>
                    <Button bsStyle="link" bsSize="small" style={{ padding: '0px' }} onClick={() => this.props.onEventClicked(event)}>
                        <Glyphicon glyph={getPreviousVersionNumber(event) === 0 ? 'plus' : 'edit'} style={{ width: '40px', position: 'static' }} />
                    </Button>
                </td>
            </tr>;
        });
    }
}


class LazyContentEvent extends React.Component {
    getHTMLContent(event) {
        return getContent(event.content, 'html') ? convertImagesToThumbnails(getContent(event.content, 'html')) : convertImagesToThumbnails(getContent(event.content, 'plainText'));
    }
    render() {
        var content = this.getHTMLContent(this.props.event);
        if (content) {
            /** For performance only events with images are lazy loaded */
            if ((this.props.event.type === NOTIFICATION) && this.props.event.previousVersionEvent) {
                return <LazyLoad>
                    <div dangerouslySetInnerHTML={{ __html: this.getHTMLContent(getOriginalEvent(this.props.event)) }} />
                    <div dangerouslySetInnerHTML={{ __html: content }} />
                </LazyLoad>;
            }
            /** For performance only events with images are lazy loaded */
            if (content.indexOf("img") !== -1) {
                return <LazyLoad once>
                    <div dangerouslySetInnerHTML={{ __html: content }} />
                </LazyLoad>;
            }
            return <div dangerouslySetInnerHTML={{ __html: content }} />;
        } else {
            return <div style={{ fontStyle: 'italic', color: '#888888' }}>  There is no content </div>
        }
    }
}