import re
import discord
from discord.ext import commands
from discord.ext.tasks import loop

regex_string = re.compile('(?:\d{4}/\d{2}/\d{2})[ ]*(?:\d{2}:\d{2}:\d{2})[ ]*(?:Group call;)[ ]*(?:TG=\d*)[ ]*(?:\[[A-Za-z]+\])?[ ]*(?:RID=(\d+))[ ]*(?:\[([-0-9A-Za-z]+)\])?[ ]*(?:[0-9]+s)?')

class Discord2Digital(commands.Cog):
    def __init__(self, bot): #, mention_group='Superadmins', channel_id=757379843792044102):
        self.bot = bot
        self.message = None
        self.last_radio_id = "-"
        self.lock = False

    @loop(seconds=.25)
    async def file_watcher(self):
        with open('C:/Users/Logan/Downloads/Installers/Cubic-Build/DSDPlus/DSDPlus.event', 'r') as event_file:
            event = event_file.readlines()[-1]
            cur_radio_id = regex_string.findall(str(event))
            if cur_radio_id and cur_radio_id != self.last_radio_id:
                self.last_radio_id = cur_radio_id
                radio_id = cur_radio_id[0][0]
                if cur_radio_id[0][1]:
                    message_name = cur_radio_id[0][1]
                embed_msg = discord.Embed(title="Last Known Radio ID", description=f"{radio_id}", color=0x00ff00)
                if 'message_name' in locals():
                    embed_msg.add_field(name="Unit Name", value=f"{message_name}", inline=True)
                await self.message.edit(embed=embed_msg)

    @commands.command(help="This command will start the display of Radio IDs and Unit names (if known) for digital comms",
                      brief="Starts the display for digital comms")
    async def display_rid(self, ctx, *, member: discord.Member = None):
        member = member or ctx.author.display_name
        if not self.lock:
            await ctx.send(f"Ok {member}, I will display the Radio IDs of digital communications")
            embed_msg = discord.Embed(title="Last Known Radio ID", description=f"-", color=0x00ff00)
            self.message = await ctx.send(embed=embed_msg)
            self.lock = True
            self.file_watcher.start()
        else:
            await ctx.send(f"{member}, there's already a display running. If you want me to stop it, @ me and say 'stop_display'")

    @commands.command(help="", brief="Stops the digital comm display")
    async def stop_display(self, ctx, member: discord.Member = None):
        member = member or ctx.author.display_name
        if self.lock:
            self.file_watcher.stop()
            await self.message.delete()
            print('Stopping monitor')
            self.lock = False
        else:
            await ctx.send(f"{member}, there's no display running. If you want me to start one, @ me and say 'display_rid'")


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