{"size": 1946, "ext": "js", "max_stars_repo_path": "client/src/js/Components/Chat.js", "max_stars_repo_name": "lis355/rps-game", "max_stars_repo_stars_event_min_datetime": "2018-09-26T00:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T07:59:05.000Z", "max_issues_repo_path": "client/src/js/Components/Chat.js", "max_issues_repo_name": "lis355/rps-game", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client/src/js/Components/Chat.js", "max_forks_repo_name": "lis355/rps-game", "max_forks_repo_forks_event_min_datetime": "2019-10-31T00:00:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T13:35:04.000Z"}
{"max_stars_count": 4, "max_issues_count": null, "max_forks_count": 2, "avg_line_length": 28.6176470588, "max_line_length": 208, "alphanum_fraction": 0.6443987667}
const React = require("react");
const ChatMessage = require("./ChatMessage");

module.exports = class Chat extends React.Component {
	constructor(props) {
		super(props);

		this.kMaxMessages = 10;

		this.state = {messages: []};
	}

	componentDidMount() {
		this.props.player.onMessage = this._addMessage.bind(this);
	}

	componentWillUnmount() {
		this.props.player.onMessage = null;
	}

	_sendMessageKey(key) {
		if (key.charCode === 13)
			this._sendMessage();
	}

	_sendMessage() {

		let messageText = this._messageInput.value;
		if (messageText) {
			this.props.player.sendMessage(messageText);
			this._messageInput.value = "";
		}
	}

	_addMessage(message) {
		let newMessges = [...this.state.messages, message];
		while (newMessges.length > this.kMaxMessages)
			newMessges.shift();

		this.setState({messages: newMessges});
	}

	componentDidUpdate() {
		this._chatMessages.scrollTop = this._chatMessages.scrollHeight;
	}

	render() {
		return (
			<div className="card chat-box m-3 flex-grow-1">
				<div className="card-body p-1 d-flex flex-column justify-content-end">
					<div className="flex-grow-1 d-flex flex-column chat-messages" ref={e => e && (this._chatMessages = e)}>
						{this.state.messages.map((message, index) => {
							return (
								<ChatMessage key={index} isOwn={message.id === this.props.player.id} text={message.text}/>
							);
						})}
					</div>
					<hr className="m-1"/>
					<div className="flex-grow-0 d-flex align-items-center chat-input-wrapper">
						<input className="form-control form-control-sm border-0 shadow-none chat-input" type="text" placeholder="Message" onKeyPress={this._sendMessageKey.bind(this)} ref={e => e && (this._messageInput = e)}/>
						<button type="button" className="btn btn-outline-primary shadow-none" onClick={this._sendMessage.bind(this)}>Send</button>
					</div>
				</div>
			</div>
		);
	}
};
