import React from "react";
import PropTypes from "prop-types";

import IDUtil from "../../util/IDUtil"; // for generating unique CSS classnames for this component

import { ResourceViewerContext } from "./ResourceViewerContext";

/*
	This component shows a popup top bar that can be used as a drag-handler for the popup using the onDrag callback
*/

export default class PopupHeader extends React.Component {
    constructor(props) {
        super(props);

        // Drag start position
        this._x = 0;
        this._y = 0;
    }

    startDrag = (e) => {
        this._x = e.pageX;
        this._y = e.pageY;
        document.addEventListener("mousemove", this.dragMove);
        document.addEventListener("mouseup", this.dragStop);
    };

    dragMove = (e) => {
        this.props.onDrag(this._x - e.pageX, this._y - e.pageY);
        this._x = e.pageX;
        this._y = e.pageY;
    };

    dragStop = (e) => {
        document.removeEventListener("mousemove", this.dragMove);
        document.removeEventListener("mouseup", this.dragStop);
    };

    render() {
        const closeButton = this.props.onClose ? (
            <div className="close-button" onClick={this.props.onClose} />
        ) : null;

        return (
            <div
                className={IDUtil.cssClassName("popup-header")}
                onMouseDown={this.startDrag}
            >
                {closeButton}
                <div className="title">{this.props.title}</div>
            </div>
        );
    }
}

PopupHeader.propTypes = {
    onClose: PropTypes.func.isRequired,
    title: PropTypes.string.isRequired,
    onDrag: PropTypes.func.isRequired,
};
