import React, { Fragment, useEffect } from 'react';
import { useStoreActions } from '../store/store.hooks';
import { ajaxActionMemoized, getMemoized } from '../ajax/ajax.utils';

interface Props {
	children: any;
}

function AuthenticationStoreContainer({ children }: Props) {
	const setToken = useStoreActions((actions) => actions.authentication.setToken);
	const setMessage = useStoreActions((actions) => actions.admin.setMessage);

	useEffect(() => {
		async function getToken() {
			const result = await ajaxActionMemoized({
				action: 'dot_press_get_token',
				method: 'get',
			});

			if (result) {
				setToken(result);
				setMessage({ title: '', content: '' });
			} else {
				setMessage({
					title: 'Welcome!',
					content: 'Great to see you! Create an account to get started',
				});
			}
		}

		getToken();
	}, []);

	return <Fragment>{children}</Fragment>;
}

export default AuthenticationStoreContainer;
