from common.networkservices import ChanServ
from common import userstatus, do_everything_to, log
from events.common import Aggressiveness, Lastact

bold = "\x02"
italic = "\x1D"
underline = "\x1F"
reverse = "\x16" 	# swap background and foreground colors ("reverse video")
reset = "\x0F"
blue = "\x0302"
green = "\x0303"
red = "\x0304"
grey = "\x0314"

def process_event(self, connection, event):
    log.info(event)
    
    kicker = event.source.nick
    channel = event.target
    kicked = event.arguments[0]
    reason = event.arguments[1]
    
    # Update last act.
    if reason:
        Lastact.update(self, kicker, "kick", channel=channel, lastact=kicked, auxiliary=reason)
        Lastact.update(self, kicked, "kicked", channel=channel, lastact=kicker, auxiliary=reason)
    else:
        Lastact.update(self, kicker, "kick", channel=channel, lastact=kicked)
        Lastact.update(self, kicked, "kicked", channel=channel, lastact=kicker)
    
    # Create user records if they don't exist.
    if not self.db.one("SELECT id FROM users WHERE name='" + kicker + "' AND network='" + self.network + "'"):   # Kicker does not have a user record.
        self.db.run("INSERT INTO \"users\" (name, network) VALUES ('" + kicker + "', '" + self.network + "')")  # Create user record.
    if not self.db.one("SELECT id FROM users WHERE name='" + kicked + "' AND network='" + self.network + "'"):  # Kicked does not have a user record.
        self.db.run("INSERT INTO \"users\" (name, network) VALUES ('" + kicked + "', '" + self.network + "')")  # Create user record.
    
    # Create kick records if they don't exist.
    if not self.db.one("SELECT id FROM kicks WHERE channel='" + channel + "'AND channel_network='" + self.network + "' AND \"user\"='" + kicker + "' AND user_network='" + self.network + "'"): # No records for kicker channel combination.
        self.db.run("INSERT INTO kicks (channel, channel_network, \"user\", user_network) VALUES ('" + channel + "', '" + self.network + "', '" + kicker + "', '" + self.network + "')")
    if not self.db.one("SELECT id FROM kicks WHERE channel='" + channel + "'AND channel_network='" + self.network + "' AND \"user\"='" + kicked + "' AND user_network='" + self.network + "'"): # No records for kicked channel combination.
        self.db.run("INSERT INTO kicks (channel, channel_network, \"user\", user_network) VALUES ('" + channel + "', '" + self.network + "', '" + kicked + "', '" + self.network + "')")
    
    # Save statistic.
    self.db.run("UPDATE kicks SET given = given + 1 WHERE channel='" + channel + "'AND channel_network='" + self.network + "' AND \"user\"='" + kicker + "' AND user_network='" + self.network + "'")
    self.db.run("UPDATE kicks SET received = received + 1 WHERE channel='" + channel + "'AND channel_network='" + self.network + "' AND \"user\"='" + kicked + "' AND user_network='" + self.network + "'")
    
    # Update protectees if needed.
    if channel == self.homechannel: # Kicked from home channel
        if event.source.nick in self.protectees:    # Protectee kicked.
            del self.protectees[event.source.nick]  # Remove old nick from list.
    
    # Do nothing more when user is not protected.
    if not userstatus.atleast_halfop(self, kicked, self.homechannel) and not kicked == connection.get_nickname():
        return
    
    # Report.
    if not channel == self.homechannel: # Not kicked from homechannel.
        if reason:
            connection.privmsg(self.homechannel, red + kicked + reset + " has been kicked from " + red + channel + reset + " by " + red + kicker + reset + ": " + green + reason)
        else:
            connection.privmsg(self.homechannel, red + kicked + reset + " has been kicked from " + red + channel + reset + " by " + red + kicker + reset + ".")
    
    # React.
    print("Reacting to kick")
    behaviour = self.db.one("SELECT aggressiveness FROM channels WHERE name='" + channel + "' AND network='" + self.network + "'")
    if behaviour == "passive":    # Passive behaviour.
        if kicked == connection.get_nickname() and channel == self.homechannel: # Bot was kicked from it's home channel.
            ChanServ.unban(connection, channel, kicked)
            ChanServ.akick_del(connection, channel, kicked)
            connection.privmsg("ChanServ", "UNBAN " + channel)
            do_everything_to.join(self, connection, self.homechannel)
    elif behaviour == "defense_only":   # Defensive behaviour.
        ChanServ.unban(connection, channel, kicked)
        ChanServ.akick_del(connection, channel, kicked)
        if kicked == connection.get_nickname(): # Bot was kicked.
            connection.privmsg("ChanServ", "UNBAN " + channel)
            do_everything_to.join(self, connection, channel)
    elif behaviour == "equal_retalliation":   # Equal retalitory behaviour.
        ChanServ.akick_del(connection, channel, kicked)
        
        # Rejoin if bot was kicked.
        if kicked == connection.get_nickname():
            connection.privmsg("ChanServ", "UNBAN " + channel)
            do_everything_to.join(self, connection, self.homechannel)
        
        if event.source.nick == connection.get_nickname() or self.channels[self.homechannel].is_owner(kicker):
            return  # Stop if offender is bot or owner.
        if not userstatus.atleast_halfop(self, kicked, self.homechannel) or not kicked == connection.get_nickname():
            return  # Stop if offended is not atleast halfop and is not the bot itself.
        if userstatus.atleast_halfop(self, kicker, self.homechannel) and not self.channels[self.homechannel].is_owner(kicked):
            return  # Stop if offender is at least halfop in the home channel and the offended is not owner.
        
        # Kick.
        do_everything_to.kick(connection, channel, kicker, Aggressiveness.retalliation_reason(self, connection, kicked, behaviour))
    
    # Battlebot behaviour.
    elif behaviour == "battlebot":
        ChanServ.akick_del(connection, channel, kicked)
        
        # Rejoin if bot was kicked.
        if kicked == connection.get_nickname():
            print("Rejoining " + channel)
            do_everything_to.join(self, connection, channel)
        
        if event.source.nick == connection.get_nickname() or self.channels[self.homechannel].is_owner(kicker):
            print("Stop if offender is bot or owner")
            return  # Stop if offender is bot or owner.
        if not userstatus.atleast_halfop(self, kicked, self.homechannel) or not kicked == connection.get_nickname():
            print("Stop if offended is not atleast halfop and is not the bot itself")
            return  # Stop if offended is not atleast halfop and is not the bot itself.
        if userstatus.atleast_halfop(self, kicker, self.homechannel) and not self.channels[self.homechannel].is_owner(kicked):
            print("Stop if offender is at least halfop in the home channel and the offended is not owner")
            return  # Stop if offender is at least halfop in the home channel and the offended is not owner.
        print("Kickbanning")

        ChanServ.tempban(connection, channel, kicker, "1h", "Aggression channel function = equal_retalliation: " + kicked)
        connection.mode(channel, "+e " + kicked)  # Excempt operator.
        ChanServ.akick_add(connection, channel, kicker) # Add kicker to ChanServs autokick.
        do_everything_to.bankick(connection, channel, kicker, event.source, "Aggression channel function = equal_retalliation: " + kicked)
