#import discord
import secrets
from discord.ext import commands
from local_settings import WEB_SCHEME, WEB_HOST
from query.guild_access_token import get_active_token, upsert_token
from common.datetime import plus10min

def setup(bot: commands.Bot):
	bot.add_cog(Admin(bot))

class Admin(commands.Cog):
	"""Administrative functionality."""

	def __init__(self, bot: commands.Bot):
		self.bot = bot

	@commands.command(
		description="Modify channel settings",
		brief="Set channel specific settings via the webgui",
		help="Sends a single-use time based token to the webportal"
	)
	@commands.has_guild_permissions(administrator=True)
	async def chanset(self, ctx: commands.Context):
		record = await get_active_token(self.bot.pg, ctx.guild.id)

		if record:	# Check for active token
			await ctx.send(f"Token {record['id']} is in use by {record['user']} until {plus10min(record['created'])}.")
		else: 
			token = secrets.token_urlsafe(40)[:40]
			await upsert_token(self.bot.pg, ctx.guild.id, ctx.author.id, token)

			await ctx.author.send(f"{WEB_SCHEME}://{WEB_HOST}/config/channel-settings/{ctx.channel.id}/{token}")	# DM token
			await ctx.send("Your access token has been sent to you in a private DM.")