"""
Rush by thepolm3.
Horray!
"""

from pyspades.constants import *
from pyspades.server import Territory
from random import randint
from twisted.internet.reactor import callLater

CP_COUNT = 4
TIME_LIMIT=5 #minutes before blue wins
WILDNESS=10

def apply_script(protocol, connection, config):
    class RushTerritory(Territory):
    
        def add_player(self, player):
            if player.team==self.protocol.blue_team and self.team!=player.team:return
            if self.team.id:move = -1
            else: move = 1
            try:
                if self.protocol.entities[self.id+move].team==self.team:return
            except Exception:
                pass
            Territory.add_player(self, player)
        
    class RushConnection(connection):

        def get_respawn_time(self):
            if self.team==self.protocol.blue_team:
                return (self.protocol.respawn_time-1)*2
            return connection.get_respawn_time(self)
            
    class RushProtocol(protocol):
        game_mode = TC_MODE

        def get_cp_entities(self):
            entities=[]
            p=WILDNESS
            add=0
            a,b,c=randint(-p,p),randint(-p,p),randint(-p,p)
            #generate a quadratic equation (ax^2)+bx+c
            p=min(16,max(1,CP_COUNT)) #gets us a value between 1 and 16
            xspread=(min(100,500/p)) #gets how spread out the tents will be
            xstart=randint(0,abs(512-(p*xspread))) #gets where to start
            xys=[]
            for i in range(p):
                x=float((xstart+xspread*i)-256)/50 #gets the x
                y=(a*(x**2))+(b*x)+c+256 #finds the y
                x=(x*50)+256 #undoes any negativity
                xys.append([x,y]) #add it to da list
                add=min(max(add,-y),512-y) #if out of bounds, add that to all tents
            for i in range(len(xys)):
                x,y=xys[i]
                y=min(max(0,y+add),512) #get the true y
                z=self.map.get_z(x,y) #get x
                cp = RushTerritory(i,self,x,y,z) #turn this indo into a territory
                cp.team=self.blue_team
                entities.append(cp) #add it to da list
            return entities #PWNAGE AT ALGEBRA

        def on_map_change(self,map):
            callLater(TIME_LIMIT*60,self.reset_game)
            return protocol.on_map_change(self,map)

    return RushProtocol, RushConnection
