from discord.ext import commands
import discord
import time
from typing import Optional
from query.channel import get_interact

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

class General(commands.Cog):
	"""General functionality."""

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


	@commands.command(
		description="Get the bot's current websocket and API latency.",
		brief="Test latency",
		help="Test latency by polling the gateway and API."
	)
	async def ping(self, ctx: commands.Context):
		start_time = time.time()
		message = await ctx.send(f"Pong!\nGateway heartbeat in {round(self.bot.latency * 1000)}ms.")
		end_time = time.time()

		await ctx.send(f"API roundtrip latency {round((end_time - start_time) * 1000)}ms.")

	@commands.command(
		description="Rubbish information.",
		brief="Get info",
		help="Display some crap."
	)
	async def info(self, ctx: commands.Context):
		"""Displays some rubbish info."""
		embed = discord.Embed(title=f"Guild: {ctx.guild}.")
		await ctx.send(embed=embed)
		#await ctx.send(f"Guild: {ctx.guild}.")

	@commands.command(
		description="Send a message",
		brief="Chat",
		help="Make a chat message",
		aliases= ("say", "pm", "dm", "echo", "print")
	)
	async def msg(self, ctx: commands.Context, channel: Optional[discord.TextChannel], user: Optional[discord.User], *, message: str = None):
		if not message:
			if channel:
				await ctx.send(f"What would you like me to say in {channel}?")
			elif user:
				await ctx.send(f"What would you like me to say to {user}?")
			else:
				await ctx.send("What would you like me to say?")
		elif channel:
			print(channel.id)
			if await get_interact(self.bot.pg, channel.id): # or await ctx.author.get_guild_permissions(channel.guild):
				await channel.send(message)
			else:
				await ctx.send(f"Interactive mode for {channel} is deactivated.")
		elif user:
			await user.send(message)
		else:
			await ctx.send(message)


	@commands.command(
		description="Change status.",
		brief="Set status",
		help="Update the bot's status."
	)
	async def status(self, ctx: commands.Context, *, text: str):
		await self.bot.change_presence(activity=discord.Game(name=text))


