import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import IDUtil from '../../../../util/IDUtil';

// A time section that is shown in a layer
// wraps the main section content
// (Is called section instead of segment, to prevent confusion with other segment entities in the data)
class Section extends React.PureComponent {
    constructor(props) {
        super(props);
        this.interaction = false;
    }

    onMouseDown = e => {
        // if ctrl is pressed, ignore the click
        if (e.ctrlKey) {
            return;
        }
        this.interaction = true;
        document.addEventListener('mousemove', this.onMouseMove);
        document.addEventListener('mouseup', this.onMouseUp);
    };

    onMouseMove = e => {
        // on mouse move, remove all event listeners
        this.removeAllListeners();
        this.interaction = false;
    };

    onMouseUp = e => {
        // can only be called on a true click when the mouse hasn't moved
        this.props.onClick(
            this.props.layerId,
            this.props.sectionId,
            this.props.start
        );
        e.stopPropagation();
    };

    removeAllListeners() {
        document.removeEventListener('mousemove', this.onMouseMove);
        document.removeEventListener('mouseup', this.onMouseUp);
    }

    componentWillUnmount() {
        // clear up the listeners
        if (this.interaction) {
            this.removeAllListeners();
        }
    }

    render() {
        const { left, width, className, active, match } = this.props;

        return (
            <div
                className={classNames(
                    IDUtil.cssClassName('tl-section'),
                    { small: width < 15, active, 'no-match': !match },
                    className
                )}
                style={{
                    transform: 'translateX(' + left + 'px)',
                    width
                    // dev redraw highlight
                    // backgroundColor: 'hsl(' + Math.random() * 360 + ',40%,80%)'
                }}
                onClick={this.onClick}
                onMouseDown={this.onMouseDown}
            >
                {this.props.children}
            </div>
        );
    }
}

Section.propTypes = {
    start: PropTypes.number.isRequired,
    left: PropTypes.number.isRequired,
    width: PropTypes.number.isRequired,
    active: PropTypes.bool,
    className: PropTypes.string,
    onClick: PropTypes.func.isRequired,
    sectionId: PropTypes.string.isRequired,
    layerId: PropTypes.string.isRequired
};

export default Section;
