import { createState, createMemo, onCleanup } from "solid-js";
import { req, on, off } from '../websocket';
import { c } from '../util';
export default function() {
	const [state, setState] = createState({
		count: 0,
		users: [],
		get authenticated() {
			return this.users.filter(user => user.logged_in).length
		}
	})
	function onAuthenticated(how, data, why) {
		switch(why) {
			case 'register':
				setState('users', state.users.length, data);
				break;
			case 'unregister':
				setState('users', state.users.filter(user => user.user_id !== data));
				break;
			default:
				setState('users', state.users.findIndex(user => user.user_id === data), 'logged_in', how === 'add');
		}
	}
	on('user/authenticated', onAuthenticated);
	function onCount(how) {
		switch(how) {
			case 'add':
				setState('count', state.count + 1);
				break;
			case 'remove':
				setState('count', state.count - 1);
				break;
		}
	}
	on('user/count', onCount);
	onCleanup(() => {
		off('user/authenticated', onAuthenticated);
		off('user/count', onCount);
	});
	req('list_users').then(setState);
	return <>
		<div>Number of visitors now: {state.count}</div>
		<div>Number of signed in users now: {state.authenticated}</div>
		<table>
			<thead>
					<tr>
						<th>id</th>
						<th>email</th>
						<th>god</th>
						<th>logged in</th>
					</tr>
				</thead>
				<tbody>
					<For each={state.users}>{user => <tr>
						<td><a href={user.user_id} onClick={c}>{user.user_id}</a></td>
						<td>{user.email}</td>
						<td><input type="checkbox" checked={user.god}/></td>
						<td>{user.logged_in ? 'yes' : 'no'}</td>
						<td><button type="button">delete</button></td>
					</tr>}</For>
				</tbody>
		</table>
	</>
}