# Path: Cogs/PickList.py
# class PickList(commands.Cog):
#     def __init__(self, bot):
#         self.bot = bot
#     # Fluff class to post the reactions we need
#     @commands.Cog.listener()
#     async def on_reaction_add(self, reaction, user):
#         self.bot.dispatch("picklist_reaction", reaction, user)
# 
#     @commands.Cog.listener()
#     async def on_reaction_remove(self, reaction, user):
#         self.bot.dispatch("picklist_reaction", reaction, user)
# 
# Path: Cogs/Message.py
# class Message:
#     def __init__(self, **kwargs):
#         # Creates a new message - with an optional setup dictionary
#         self.max_chars = 2000
#         self.pm_after = kwargs.get("pm_after", 1) # -1 to disable, 0 to always pm
#         self.force_pm = kwargs.get("force_pm", False)
#         self.header = kwargs.get("header", "")
#         self.footer = kwargs.get("footer", "")
#         self.pm_react = kwargs.get("pm_react", "📬")
#         self.message = kwargs.get("message", None)
#         self.file = kwargs.get("file", None) # Accepts a file path
#         self.max_pages = 0
#         self.delete_after = kwargs.get("delete_after",None)
# 
#     def _get_file(self, file_path):
#         if not os.path.exists(file_path):
#             return None
#         # Path exists, let's get the extension if there is one
#         ext = file_path.split(".")
#         fname = "Upload." + ext[-1] if len(ext) > 1 else "Upload"
#         file_handle = discord.File(fp=file_path, filename=fname)
#         return (file_handle, fname)
# 
#     async def _send_message(self, ctx, message, pm = False, file_path = None):
#         # Helper method to send embeds to their proper location
#         send_file = None
#         if not file_path == None:
#             dfile = self._get_file(file_path)
#             if not dfile:
#                 # File doesn't exist...
#                 try:
#                     await ctx.send("An error occurred!\nThe file specified couldn't be sent :(")
#                 except:
#                     # We tried...
#                     pass
#                 return None
#             else:
#                 # Setup our file
#                 send_file = dfile[0]
#         if pm == True and type(ctx) is discord.ext.commands.Context and not ctx.channel == ctx.author.dm_channel:
#             # More than 2 pages - try to dm
#             try:
#                 message = await ctx.author.send(message, file=send_file, delete_after=self.delete_after)
#                 await ctx.message.add_reaction(self.pm_react)
#                 return message
#             except discord.Forbidden:
#                 if self.force_pm:
#                     # send an error message
#                     try:
#                         await ctx.send("An error occurred!\nCould not dm this message to you :(")
#                     except:
#                         # We tried...
#                         pass
#                     return None
#                 pass
#         return await ctx.send(message, file=send_file, delete_after=self.delete_after)
# 
#     async def send(self, ctx):
#         if not ctx or not self.message or not len(self.message):
#             return
#         text_list = textwrap.wrap(
#             self.message,
#             self.max_chars - len(self.header) - len(self.footer),
#             break_long_words=True,
#             replace_whitespace=False)
# 
#         # Only pm if our self.pm_after is above -1
#         to_pm = len(text_list) > self.pm_after if self.pm_after > -1 else False
#         page_count = 1
#         for m in text_list:
#             if self.max_pages > 0 and page_count > self.max_pages:
#                 break
#             message = await self._send_message(ctx, self.header + m + self.footer, to_pm)
#             # Break if things didn't work
#             if not message:
#                 return None
#             page_count += 1
#         return message


import asyncio, discord, re
from   discord.ext import commands
from   Cogs import PickList, Message

	async def watchboturls(self, ctx, *, yes_no = None):
		"""Sets whether we watch for URLs from other bots (bot-admin only - disabled by default)."""
		if not self.is_bot_admin(ctx):
			return await ctx.send("You do not have sufficient privileges to access this command.")
		setting_name = "Watch bot URLs"
		setting_val  = "URLWatchListAllowBots"
		current = self.settings.getServerStat(ctx.guild, setting_val, False)
		if yes_no == None:
			msg = "{} currently *{}.*".format(setting_name,"enabled" if current else "disabled")
		elif yes_no.lower() in [ "yes", "on", "true", "enabled", "enable" ]:
			yes_no = True
			msg = "{} {} *enabled*.".format(setting_name,"remains" if current else "is now")
		elif yes_no.lower() in [ "no", "off", "false", "disabled", "disable" ]:
			yes_no = False
			msg = "{} {} *disabled*.".format(setting_name,"remains" if not current else "is now")
		else:
			msg = "That's not a valid setting."
			yes_no = current
		if not yes_no == None and not yes_no == current:
			self.settings.setServerStat(ctx.guild, setting_val, yes_no)
		await ctx.send(msg)
	
	@commands.command()
	async def lasturls(self, ctx):
		"""Shows up to the last 200 URLs sent that matched the URL watch lists in order of most recent to least."""
		url_matches = self.settings.getServerStat(ctx.guild,"URLWatchListMatches",[])
		if not url_matches:
			return await Message.EmbedText(description="I haven't seen any matches yet.",title="Watched URL Matches",color=ctx.author).send(ctx)
		# Let's create our list now
		entries = [{"name":"{}. {}".format(y+1,x["url"]),"value":"└─ From <@!{}> - [Link]({})".format(x["from"],x["link"])} for y,x in enumerate(url_matches)]

# Path: Cogs/PickList.py
# class PickList(commands.Cog):
#     def __init__(self, bot):
#         self.bot = bot
#     # Fluff class to post the reactions we need
#     @commands.Cog.listener()
#     async def on_reaction_add(self, reaction, user):
#         self.bot.dispatch("picklist_reaction", reaction, user)
# 
#     @commands.Cog.listener()
#     async def on_reaction_remove(self, reaction, user):
#         self.bot.dispatch("picklist_reaction", reaction, user)
# 
# Path: Cogs/Message.py
# class Message:
#     def __init__(self, **kwargs):
#         # Creates a new message - with an optional setup dictionary
#         self.max_chars = 2000
#         self.pm_after = kwargs.get("pm_after", 1) # -1 to disable, 0 to always pm
#         self.force_pm = kwargs.get("force_pm", False)
#         self.header = kwargs.get("header", "")
#         self.footer = kwargs.get("footer", "")
#         self.pm_react = kwargs.get("pm_react", "📬")
#         self.message = kwargs.get("message", None)
#         self.file = kwargs.get("file", None) # Accepts a file path
#         self.max_pages = 0
#         self.delete_after = kwargs.get("delete_after",None)
# 
#     def _get_file(self, file_path):
#         if not os.path.exists(file_path):
#             return None
#         # Path exists, let's get the extension if there is one
#         ext = file_path.split(".")
#         fname = "Upload." + ext[-1] if len(ext) > 1 else "Upload"
#         file_handle = discord.File(fp=file_path, filename=fname)
#         return (file_handle, fname)
# 
#     async def _send_message(self, ctx, message, pm = False, file_path = None):
#         # Helper method to send embeds to their proper location
#         send_file = None
#         if not file_path == None:
#             dfile = self._get_file(file_path)
#             if not dfile:
#                 # File doesn't exist...
#                 try:
#                     await ctx.send("An error occurred!\nThe file specified couldn't be sent :(")
#                 except:
#                     # We tried...
#                     pass
#                 return None
#             else:
#                 # Setup our file
#                 send_file = dfile[0]
#         if pm == True and type(ctx) is discord.ext.commands.Context and not ctx.channel == ctx.author.dm_channel:
#             # More than 2 pages - try to dm
#             try:
#                 message = await ctx.author.send(message, file=send_file, delete_after=self.delete_after)
#                 await ctx.message.add_reaction(self.pm_react)
#                 return message
#             except discord.Forbidden:
#                 if self.force_pm:
#                     # send an error message
#                     try:
#                         await ctx.send("An error occurred!\nCould not dm this message to you :(")
#                     except:
#                         # We tried...
#                         pass
#                     return None
#                 pass
#         return await ctx.send(message, file=send_file, delete_after=self.delete_after)
# 
#     async def send(self, ctx):
#         if not ctx or not self.message or not len(self.message):
#             return
#         text_list = textwrap.wrap(
#             self.message,
#             self.max_chars - len(self.header) - len(self.footer),
#             break_long_words=True,
#             replace_whitespace=False)
# 
#         # Only pm if our self.pm_after is above -1
#         to_pm = len(text_list) > self.pm_after if self.pm_after > -1 else False
#         page_count = 1
#         for m in text_list:
#             if self.max_pages > 0 and page_count > self.max_pages:
#                 break
#             message = await self._send_message(ctx, self.header + m + self.footer, to_pm)
#             # Break if things didn't work
#             if not message:
#                 return None
#             page_count += 1
#         return message


# Path: Cogs/WatchURL.py
import asyncio, discord, re
from   discord.ext import commands
from   Cogs import PickList, Message

	async def watchboturls(self, ctx, *, yes_no = None):
		"""Sets whether we watch for URLs from other bots (bot-admin only - disabled by default)."""
		if not self.is_bot_admin(ctx):
			return await ctx.send("You do not have sufficient privileges to access this command.")
		setting_name = "Watch bot URLs"
		setting_val  = "URLWatchListAllowBots"
		current = self.settings.getServerStat(ctx.guild, setting_val, False)
		if yes_no == None:
			msg = "{} currently *{}.*".format(setting_name,"enabled" if current else "disabled")
		elif yes_no.lower() in [ "yes", "on", "true", "enabled", "enable" ]:
			yes_no = True
			msg = "{} {} *enabled*.".format(setting_name,"remains" if current else "is now")
		elif yes_no.lower() in [ "no", "off", "false", "disabled", "disable" ]:
			yes_no = False
			msg = "{} {} *disabled*.".format(setting_name,"remains" if not current else "is now")
		else:
			msg = "That's not a valid setting."
			yes_no = current
		if not yes_no == None and not yes_no == current:
			self.settings.setServerStat(ctx.guild, setting_val, yes_no)
		await ctx.send(msg)
	
	@commands.command()
	async def lasturls(self, ctx):
		"""Shows up to the last 200 URLs sent that matched the URL watch lists in order of most recent to least."""
		url_matches = self.settings.getServerStat(ctx.guild,"URLWatchListMatches",[])
		if not url_matches:
			return await Message.EmbedText(description="I haven't seen any matches yet.",title="Watched URL Matches",color=ctx.author).send(ctx)
		# Let's create our list now
		entries = [{"name":"{}. {}".format(y+1,x["url"]),"value":"└─ From <@!{}> - [Link]({})".format(x["from"],x["link"])} for y,x in enumerate(url_matches)]

		await PickList.PagePicker(title="Watched URL Matches",list=entries,ctx=ctx).pick()
