import React, { useRef, useContext } from 'react';

import { TokenContext } from '../utilities/token-provider';

const GrantMod = props => {
	//context
	const authTokens = useContext(TokenContext);

	//ref
	const usernameRef = useRef();

	return (
		<div>
			<h2 className='centered'>Grant Moderation Privileges</h2>
			<form>
				<div>
					<label htmlFor='username'>Username:</label>
					<input type='text' name='username' ref={usernameRef} />
				</div>

				<button type='button' onClick={async evt => {
					evt.preventDefault();
					const [err, result] = await handleButtonPress(usernameRef.current.value, authTokens.tokenFetch, 'POST');

					if (err) {
						alert(err);
					}

					if (result) {
						alert('mod set');
						usernameRef.current.value = '';
					}
				}}>Submit</button>

				<button type='button' onClick={async evt => {
					evt.preventDefault();
					const [err, result] = await handleButtonPress(usernameRef.current.value, authTokens.tokenFetch, 'DELETE');

					if (err) {
						alert(err);
					}

					if (result) {
						alert('mod removed');
						usernameRef.current.value = '';
					}
				}}>Remove</button>
			</form>
		</div>
	);
};

const handleButtonPress = async (username, tokenFetch, method) => {
	const result = await tokenFetch(`${process.env.AUTH_URI}/admin/mod`, {
		method: method,
		headers: {
			'Content-Type': 'application/json',
			'Access-Control-Allow-Origin': '*'
		},
		body: JSON.stringify({
			username
		})
	});

	if (!result.ok) {
		const err = `${result.status}: ${await result.text()}`;
		console.log(err);
		return [err, false];
	}

	return [null, true];
};

export default GrantMod;
