import datetime, asyncpg
from common.datetime import min10min
from query.guild import update_guild

async def get_active_token(pg, guild_id):
	return await pg.fetchrow("SELECT * FROM guild_access_token WHERE guild=$1 AND created > $2", guild_id, min10min(datetime.datetime.now()))

async def upsert_token(pg, guild_id, user_id, token):
	print(token)
	print("INSERT INTO guild_access_token(guild, \"user\", token) VALUES($1, $2, $3)", guild_id, user_id, token)

	try:
		await pg.execute("INSERT INTO guild_access_token(guild, \"user\", token) VALUES($1, $2, $3)", guild_id, user_id, [token])
		
		# ON CONFLICT() DO UPDATE SET \"user\"=$1 AND token=$2", user_id, token)
	except asyncpg.exceptions.ForeignKeyViolationError:
		await update_guild(self.bot.pg, message.guild)
		await pg.execute("INSERT INTO guild_access_token(guild, \"user\", token) VALUES($1, $2, $3)", guild_id, user_id, token)
		# ON CONFLICT() DO UPDATE SET \"user\"=$1 AND token=$2", user_id, token)