import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import classnames from 'classnames';
import * as appPropTypes from './appPropTypes';
import * as requestActions from '../redux/requestActions';

const Sidebar = ({
	toolbarsVisible, me, screenProducer, onLogin, onShareScreen,
	onUnShareScreen, onNeedExtension, onLeaveMeeting
}) =>
{
	let screenState;
	let screenTip;

	if (me.needExtension)
	{
		screenState = 'need-extension';
		screenTip = 'Install screen sharing extension';
	}
	else if (!me.canShareScreen)
	{
		screenState = 'unsupported';
		screenTip = 'Screen sharing not supported';
	}
	else if (screenProducer)
	{
		screenState = 'on';
		screenTip = 'Stop screen sharing';
	}
	else
	{
		screenState = 'off';
		screenTip = 'Start screen sharing';
	}

	return (
		<div className={classnames('sidebar room-controls', {
			'visible' : toolbarsVisible
		})}
		>
			<div
				className={classnames('button', 'screen', screenState)}
				data-tip={screenTip}
				data-type='dark'
				onClick={() =>
				{
					switch (screenState)
					{
						case 'on':
						{
							onUnShareScreen();
							break;
						}
						case 'off':
						{
							onShareScreen();
							break;
						}
						case 'need-extension':
						{
							onNeedExtension();
							break;
						}
						default:
						{
							break;
						}
					}
				}}
			/>

			{me.loginEnabled ?
				<div
					className={classnames('button', 'login', 'off', {
						disabled : me.loginInProgress
					})}
					data-tip='Login'
					data-type='dark'
					onClick={() => onLogin()}
				/>
				:null
			}

			<div
				className={classnames('button', 'leave-meeting')}
				data-tip='Leave meeting'
				data-type='dark'
				onClick={() => onLeaveMeeting()}
			/>
		</div>
	);
};

Sidebar.propTypes = {
	toolbarsVisible : PropTypes.bool.isRequired,
	me              : appPropTypes.Me.isRequired,
	onShareScreen   : PropTypes.func.isRequired,
	onUnShareScreen : PropTypes.func.isRequired,
	onNeedExtension : PropTypes.func.isRequired,
	onLeaveMeeting  : PropTypes.func.isRequired,
	onLogin         : PropTypes.func.isRequired,
	screenProducer  : appPropTypes.Producer
};

const mapStateToProps = (state) =>
	({
		toolbarsVisible : state.room.toolbarsVisible,
		screenProducer  : Object.values(state.producers)
			.find((producer) => producer.source === 'screen'),
		me : state.me
	});

const mapDispatchToProps = {
	onLeaveMeeting  : requestActions.leaveRoom,
	onShareScreen   : requestActions.enableScreenSharing,
	onUnShareScreen : requestActions.disableScreenSharing,
	onNeedExtension : requestActions.installExtension,
	onLogin         : requestActions.userLogin
};

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(Sidebar);