from math import pi, cos, sin
from random import random

from panda3d.core import Vec3

import helper
from helper import base, STARS, PAUSED
from people.police import Police
from people.player import instance as player
from city import instance as city


MIN_SPAWN_DISTANCE = 10
MAX_SPAWN_DISTANCE = 30
MAX_ACTIVE = [0, 4, 7, 9, 10, 15, 15, 20, 30, 40, 50]
GROUP_SIZE = [0, 1, 1, 2,  3,  3,  4,  4,  5,  5, 5]
DELAY   = [0, 30, 20, 30, 30, 20, 30, 20, 30, 20, 10]

DEBUG = False


def spawn(task):
    if DEBUG: print("spawning police")
    stars = STARS[0]
    if DEBUG: print("stars", stars)
    task.delayTime = DELAY[stars]

    if PAUSED[0]:
        if DEBUG: print("paused")
        return task.again

    if DEBUG: print("living", helper.living_police)
    if helper.living_police >= MAX_ACTIVE[stars] or GROUP_SIZE[stars] == 0:
        if DEBUG: print("early exit")
        # early exit
        return task.again

    PANIC = 100
    while True:
        PANIC -= 1
        if PANIC <= 0:
            print("POLICE PANIC!")
            return task.again
        dist = random() * (MAX_SPAWN_DISTANCE - MIN_SPAWN_DISTANCE) + MIN_SPAWN_DISTANCE
        angle = random() * 2 * pi
        x = cos(angle) * dist
        y = sin(angle) * dist
        x += player.pos.x
        y += player.pos.y
        if city.on_road(x, y):
            break
    for _ in range(GROUP_SIZE[stars]):
        if helper.living_police >= MAX_ACTIVE[stars]:
            if DEBUG: print('reached max cop')
            break
        if DEBUG: print("spawning cop at", x, y)
        Police(Vec3(x, y, 0))
    return task.again

base.task_mgr.add(spawn)