import random
from src.components.Table import Table, Status
from src.components.Waiter import Waiter
import pygame
#drawable objects manager
class DrawableCollection:
    #const, minimal distance between objects
    __MinDistance = 0

    def __init__(self):
        #collection that holds all drawable objects
        self.__drawables = []
        self.image = pygame.transform.scale((pygame.image.load('./images/Backgroud.png')),(1700,1100))

    #adds drawable objects to the collection
    def add(self, drawable):
        self.__drawables.append(drawable)

    #generates and sets random (x, y) and cheks if it's not occupied by other object
    def generatePosition(self, drawable):
        isPositionUnique = False
        while not isPositionUnique:
            x = random.randint(drawable.getMinX() + 1, drawable.getMaxX() - 1)
            y = random.randint(drawable.getMinY() + 1, drawable.getMaxY() - 1)
            isPositionUnique = True
            for item in self.__drawables:
                if abs(item.getX() - x) <= self.__MinDistance and abs(item.getY() - y) <= self.__MinDistance:
                    isPositionUnique = False
                    break
            if isPositionUnique:
                drawable.setX(x)
                drawable.setY(y)

    #draws all objects stored in collection
    def draw(self, screen):
        screen.blit(self.image, (0, 0))
        for item in self.__drawables:
            item.draw(screen)

    #checks if position (x,y) is not occupied by other object
    def isPositionAvailable(self, x, y):
        isPositionAvailable = True
        for item in self.__drawables:
            if item.getX() == x and item.getY() == y:
                isPositionAvailable = False
                break
        return isPositionAvailable

    #gets all tables by status from collection
    def getTables(self, status):
        result = []
        for item in self.__drawables:
            if isinstance(item, Table) and item.isStatus(status):
                result += [item]
        return result

    #gets all waiters from collection
    def getWaites(self):
        result = []
        for item in self.__drawables:
            if isinstance(item, Waiter):
                result += [item]
        return result

    #waiter collects order from the nearest table
    def collectOrders(self):
        waiters = self.getWaites()
        for waiter in waiters:
            tables = self.getTables(Status.Ready)
            for table in tables:
                if (table.getX() == waiter.getX() and abs(table.getY() - waiter.getY()) == 1) or (table.getY() == waiter.getY() and abs(table.getX() - waiter.getX()) == 1):
                    table.setStatus(Status.Waiting)
                    waiter.addOrder(table)
                    table.delOrder()