#explode by Kuma
#Version 4

from commands import add, admin, alias, get_player
from pyspades.server import grenade_packet
from pyspades.world import Grenade
from pyspades.common import Vertex3

from random import randint, random
from math import floor, sqrt, pi, cos, sin

INVALID_FORMAT = "WRONG INPUT"

@alias('e')
@admin
def explode(connection, player = None):
    protocol = connection.protocol
    if not player is None:
        player = get_player(protocol, player)
        player_obj = player.world_object
        position = player_obj.position
        x, y, z = position.x, position.y, position.z
        grenade_spawn(player, x, y, z)
    else:
        connection.send_chat(INVALID_FORMAT)

@alias('ce')
@admin
def cexplode(connection, player = None, number = 10):
    protocol = connection.protocol
    number = int(number) if number != 10 else number #I don't know what I was think when I wrote this
    if player is not None and number <= 250:
        player = get_player(protocol, player)
        radius = round(number / 3) #This was going to more complicated but I decided not to
        player_obj = player.world_object
        position = player_obj.position
        x1, y1 = position.x, position.y
        for turn in xrange(number):
            t = 2*pi*round(random(), 4)
            r = radius*sqrt(round(random(), 4))
            x = x1 + r*cos(t)
            y = y1 + r*sin(t)
            z = position.z
            grenade_spawn(connection, x, y, z, fuse = 2.5)
    else:
        connection.send_chat(INVALID_FORMAT)

add(explode)
add(cexplode)

#This function is useful for doing grenade related stuff
def grenade_spawn(connection, x, y, z, fuse = 1, z_block = 10):
    protocol = connection.protocol
    x, y, z = floor(x), floor(y), floor(z) - z_block #This is for centering them on the blocks
    v_position = Vertex3(x, y, z)
    grenade = protocol.world.create_object(Grenade, fuse, v_position, None, Vertex3(0, 0, 0), connection.grenade_exploded)
    grenade_packet.player_id = connection.player_id
    grenade_packet.value = grenade.fuse
    grenade_packet.position = grenade.position.get()
    grenade_packet.velocity = grenade.velocity.get()
    protocol.send_contained(grenade_packet)

def apply_script(protocol, connection, config):
    return protocol, connection