
{h} = require "maquette"

UsersCache = (authd-ws, on-user) ->
	self = {}

	on-user ||= (user) ->

	# uid => user | "request sent"
	# FIXME: "request sent" stays forever that way on failure.
	self.users = {}

	# TODO: We’ll probably want to handle “no such user” errors.
	authd-ws.add-event-listener \user, (message) ->
		user = message.user

		self.users[user.uid] := user
		self.users[user.login] := user

		on-user user

	authd-ws.add-event-listener \error, (message) ->
		if message.reason == "user not found"
			console.log "warning: got a “user not found” error"

	self.render-user = (uid) ->
		if user = self.get-user uid
			h \div.level.user {key: "user-#{uid}"} [
				h \div.level-left [
					console.log "#{user.login}", user.profile?.avatar
					if avatar = user.profile?.avatar
						h \div.level-item [
							h \figure.image.is-32x32.is-rounded [
								h \img {
									src: avatar
									alt: ""
								}
							]
						]

					h \div.level-item [
						"@" + (user.profile?.full_name || user.login)
					]
				]
			]

	# Note: uid may also be a login.
	self.get-user = (uid, request-if-missing = true) ->
		switch user = self.users[uid]
		when void
			if request-if-missing
				console.log "Sending request for #{uid}"
				self.users[uid] = "request sent"
				authd-ws.get-user uid

			void
		when "request sent"
			void
		else
			user

	self

module.exports = UsersCache

