import logging
from datetime import datetime

from discord.embeds import Embed

from utils.messaging import Paginate, notify_owner

from .discordrelay import DiscordRelay
from .jabberrelay import JabberRelay


class PingAggregator:
    '''A cog which connects to config defined xmpp servers and relays messages
    from certain senders to the config defined channel'''
    def __init__(self, bot, config):
        self.logger = logging.getLogger(__name__)
        self.bot = bot
        self.relays = []
        self.last_msg = None

        self.create_clients(config)

    def create_clients(self, config):
        'Creates an JabberRelay client for each server specified'
        for jabber_config in config.get("jabber_relays", []):
            self.relays.append(JabberRelay(self.bot, jabber_config, self.logger))
        for discord_config in config.get("discord_relays", []):
            self.relays.append(DiscordRelay(self.bot, discord_config))

    def get_health(self):
        'Returns a string describing the status of this cog'
        if self.relays:
            response = ''
            for relay in self.relays:
                response += relay.get_health()
        else:
            response = '\n  \u2716 No relays initialised'
        return response

    async def on_broadcast(self, package):
        'Relay message to discord, ignore if it is a duplicate'
        body = package['body'].replace(' || ', '\n')

        idx = body.rfind('Broadcast sent at ')
        raw_msg = body[:idx] if idx > 0 else body

        if raw_msg != self.last_msg:
            self.last_msg = raw_msg
            self.logger.info(
                'Relaying message from %s', package['sender']
            )

            embeds = []
            paginate = Paginate(body, enclose=('', ''), page_size=1900)
            for page in paginate:
                embed = self.ping_embed(package, page, paginate)
                embeds.append(embed)

            for destination in package['destinations']:
                channel_id = destination['channel_id']
                channel = self.bot.get_channel(channel_id)

                if channel:
                    embed = embeds[0]
                    await self.bot.send_message(
                        channel, embed=embed, content=destination.get('prefix')
                    )  # Only show prefix on first page.
                    for embed in embeds[1:]:
                        await self.bot.send_message(channel, embed=embed)
                else:
                    await notify_owner(
                        self.bot,
                        ['Invalid channel: {}'.format(channel_id)]
                    )
        else:
            self.logger.info('Ignored duplicate message from %s',
                             package['sender'])

    @staticmethod
    def ping_embed(package, message, paginate):
        'Formats and generates the embed for the ping'
        embed = Embed()
        currentmsg = paginate.pages_yielded
        totalmsgs = currentmsg + paginate.pages_left

        if currentmsg == 1:
            embed.title = package['sender']
            embed.set_author(name=package['description'])

        embed.description = message
        embed.set_thumbnail(url=package['logo_url'])
        if totalmsgs > 1:
            embed.set_footer(
                text='Message {}/{}'.format(currentmsg, totalmsgs)
            )
        embed.timestamp = datetime.utcnow()
        embed.colour = package['embed_colour']

        return embed

    def __unload(self):
        for relay in self.relays:
            relay.disconnect()

@@ -500,37 +500,8 @@
 = %5B%5D
-%0A        self.last_msg = None
 %0A%0A  
@@ -1349,237 +1349,8 @@
 te'%0A
-        body = package%5B'body'%5D.replace(' %7C%7C ', '%5Cn')%0A%0A        idx = body.rfind('Broadcast sent at ')%0A        raw_msg = body%5B:idx%5D if idx %3E 0 else body%0A%0A        if raw_msg != self.last_msg:%0A            self.last_msg = raw_msg%0A    
     
@@ -1371,20 +1371,16 @@
 r.info(%0A
-    
         
@@ -1421,36 +1421,32 @@
 ckage%5B'sender'%5D%0A
-    
         )%0A%0A     
@@ -1444,28 +1444,24 @@
  )%0A%0A        
-    
 embeds = %5B%5D%0A
@@ -1460,20 +1460,16 @@
 ds = %5B%5D%0A
-    
         
@@ -1532,28 +1532,24 @@
 00)%0A        
-    
 for page in 
@@ -1562,36 +1562,32 @@
 te:%0A            
-  
-  
 embed = self.pin
@@ -1627,28 +1627,24 @@
             
-    
 embeds.appen
@@ -1657,28 +1657,24 @@
 d)%0A%0A        
- 
-   
 for destinat
@@ -1705,20 +1705,16 @@
 ions'%5D:%0A
-    
         
@@ -1764,28 +1764,24 @@
             
-    
 channel = se
@@ -1820,28 +1820,24 @@
             
-   
- 
 if channel:%0A
@@ -1836,20 +1836,16 @@
 hannel:%0A
-    
         
@@ -1878,36 +1878,32 @@
                 
-  
-  
 await self.bot.s
@@ -1915,20 +1915,16 @@
 essage(%0A
-    
         
@@ -2007,20 +2007,16 @@
         
-    
 )  # Onl
@@ -2044,20 +2044,16 @@
 t page.%0A
-    
         
@@ -2097,36 +2097,32 @@
                 
-    
 await self.bot.s
@@ -2163,38 +2163,30 @@
             
-    
 else:%0A
-    
             
@@ -2225,28 +2225,24 @@
             
-  
-  
 self.bot,%0A  
@@ -2239,20 +2239,16 @@
 lf.bot,%0A
-    
         
@@ -2322,140 +2322,8 @@
     
-    )%0A        else:%0A            self.logger.info('Ignored duplicate message from %25s',%0A                             package%5B'sender'%5D
 )%0A%0A 

Remove duplicate filtering