import pygame
import variables
import settings
import utils
from copy import copy
from objects import Player


class ObjectsList(object):

    def __init__(self):
        self.objects = []
        self.player = None

    @property
    def get_player(self):
        return self.player

    @property
    def get_count(self):
        return len(self.objects)

    def add(self, _object):
        self.objects.append(_object)
        if isinstance(_object, Player):
            self.player = _object

    def print(self):
        for _object in self.objects:
            print(_object)

    #@utils.timer
    def find_collisions(self):
        #objects = list.copy(self.objects)

        for object_i in self.objects:
            object_i.delete_collisions()

        for index, object_i in enumerate(self.objects):
            if not object_i.has_body:
                continue

            for object_j in self.objects[:index + 1]:
                if not object_j.has_body:
                    continue

                if object_i != object_j:
                    distance = ((object_j.get_x - object_i.get_x) *
                                (object_j.get_x - object_i.get_x) +
                                (object_j.get_y - object_i.get_y) *
                                (object_j.get_y - object_i.get_y)) ** 0.5

                    radius = object_i.collision_radius + object_j.collision_radius

                    if distance < radius:
                        if not object_i.collision_exceptions.count(object_j.owner):
                            object_i.add_collision(copy(object_j))
                            object_j.add_collision(copy(object_i))

                    if settings.DEBUG and settings.SHOW_COLLISION:
                        pygame.draw.line(variables.screen, 'grey',
                                         [object_i.get_x, object_i.get_y],
                                         [object_j.get_x, object_j.get_y])

    def update(self):
        self.find_collisions()
        for _object in self.objects:
            _object.check_collisions()

            if not _object.has_live:
                if _object.type == 'ship' and _object.owner == 'player':
                    variables.game_start = False
                self.objects.remove(_object)
            else:
                _object.update()

    def render(self):
        self.update()
        for _object in self.objects:
            _object.render()

