import * as React from 'react';
import { useUserLogin } from '../../hooks/user';
import { RouteComponentProps } from 'react-router-dom';
import storage from '../../utils/storage';

const TempLogin: React.FC<RouteComponentProps> = ({ history }) => {
	const [loginState, requestLogin] = useUserLogin();
	React.useEffect(() => {
		const search = location.search;
		let token = '';
		if (search.split('?').length > 0) {
			for (let i = 0; i < search.split('?')[1].split('&').length; i++) {
				const query = search
					.split('?')[1]
					.split('&')
					[i].split('=');
				if (query[0] === 'token' && !!query[1]) {
					token = query[1];
					break;
				}
			}
		}
		requestLogin({ user: '', password: '', rember_password: false }, { token })
			.then((response) => {
				storage.setItem('uid', response.uid);
				storage.setItem('token', response.token);
				storage.setItem('username', response.username);
				storage.setItem('refresh_token', response.refresh_token);
				history.push('/');
			})
			.catch(() => {
				localStorage.clear();
				location.href = '/login';
			});
	}, []);
	return null;
};
export default TempLogin;
