import { Meteor } from 'meteor/meteor';
import {Roles} from 'meteor/alanning:roles';
import React, { useState } from 'react';
import { useTracker } from 'meteor/react-meteor-data';
import {Link} from 'react-router-dom';
import _ from 'lodash';

export const Page = (props) => {
	const {user, canManageLaptops, isAdmin} = useTracker(() => {
		const user = Meteor.user();
		const canManageLaptops = user && Roles.userIsInRole(user._id, 'laptop-management', 'global');
		const isAdmin = user && Roles.userIsInRole(user._id, 'admin', 'global');

		return {
			user,
			canManageLaptops,
			isAdmin
		}
	})

	function performLogin() {
		//Login style can be "popup" or "redirect".  I am not sure we need to request and offline token.
		Meteor.loginWithGoogle({loginStyle: "popup", requestOfflineToken: true}, (err) => {
			if (err) {
				console.log(err);
			} else {
				//console.log("Logged in");
			}
		})
	}

	function performLogout() {
		Meteor.logout();
	}

	return (
		<div>
			<div className='pageHeaderContainer'>
				<div className="container">
					<header className="row pageHeader">
						<div className="col-12 logoContainer">
							<img className="logo" src="/images/logo.svg" alt="Logo"/>
							<div className="login">
								{!user ?
									<button type="button" role="button" onClick={performLogin}>Login</button>
									:
									<button type="button" role="button" onClick={performLogout}>Logout</button>
								}
							</div>
						</div>
						<div className="col-12 center title">K12 Tempest</div>
						<div className="col-12 center">
							<div className="nav-separator"/>
						</div>
					</header>
				</div>
			</div>
			<div className='pageNavContainer'>
				<div className='container'>
					<header className='row pageNavHeader'>
						<nav className="col-12 center">
							<Link to='/'>Home</Link>
							{canManageLaptops && <Link to="/history">History</Link>}
							{canManageLaptops && <Link to="/assignments">Assignments</Link>}
							{isAdmin && <Link to="/assets">Assets</Link>}
							{isAdmin && <Link to="/users">Users</Link>}
							{isAdmin && <Link to="/admin">Admin</Link>}
						</nav>
					</header>
				</div>
			</div>
			<div className='pageContentContainer'>
				{props.children}
			</div>
		</div>
	)
}