import { Accounts } from 'meteor/accounts-base'
import { Roles } from 'meteor/alanning:roles'
import {Meteor} from "meteor/meteor";

console.log("Setting up accounts-config...")

if(Meteor.isClient) {
	Accounts.ui.config({
	    passwordSignupFields: 'USERNAME_ONLY'
	});
}

Accounts.config({
	// Allow only certain email domains.
	restrictCreationByEmailDomain: function(address) {
		let pattern = process.env.EMAIL_REGEX;

		return new RegExp(pattern, 'i').test(address)
	}
});

if(Meteor.isServer) {
	let adminEmail = process.env.ADMIN_EMAIL;
	let watchForAdmin = false;

	//Setup the roles.
	Roles.createRole('admin', {unlessExists: true});
	Roles.createRole('laptop-management', {unlessExists: true});
	Roles.addRolesToParent('laptop-management', 'admin', {unlessExists: true});
	//Roles.addUsersToRoles("zwbMiaSKHix4bWQ8d", 'admin', 'global', {unlessExists: true});

	// If we are passed an email address that should be admin by default, then ensure that user is admin, or mark it as needing to be admin if the user ever logs in.
	// Given that this app requires Google OAuth2, and we expect logins to be restricted to district email addresses, this should be very secure.
	if(adminEmail) {
		let user = Meteor.users.findOne({"services.google.email": adminEmail});

		if(user) {
			let assignment = Meteor.roleAssignment.findOne({'user._id': user._id, "role._id": "admin"});

			// console.log("Admin Role Assignment: " + JSON.stringify(assignment));
			if(!assignment) {
				Roles.addUsersToRoles(user._id, ['admin']);
			}
		}
		else {
			watchForAdmin = true;
		}
	}

	// Listen for users logging in so we can setup the admin user automatically once they log in the first time.
	if(watchForAdmin) {
		// TODO: It would be nice to remove this handler after the admin user is found, but the docs are pretty ambiguous about how to do that.  Not a big deal, just annoying.
		Accounts.onLogin(function (data) {
			// console.log("User logged in:");
			// console.log(data.user.services.google.email);

			// data.user == Meteor.user()

			//console.log(JSON.stringify(Meteor.user()));
			if (watchForAdmin) {
				try {
					if (data.user.services.google.email === adminEmail) {
						Roles.addUsersToRoles(data.user._id, ['admin']);
						watchForAdmin = false;
					}
				} catch (err) {
					console.log(err);
				}
			}
		});
	}
}

console.log("Finished setting up accounts-config.")