from .unit import Unit
from .rat import Rat
from engine.collision_system import CollisionLayer
import random

# Costanti
AGE_THRESHOLD = 200

class Gas(Unit):
    def __init__(self, game, position=(0,0), id=None, parent_id=None):
        super().__init__(game, position, id, collision_layer=CollisionLayer.GAS)
        self.parent_id = parent_id
        # Specific attributes for gas
        self.speed = 50
        self.fight = False
        self.age = 0
        if parent_id:
            self.age = round(random.uniform(0, AGE_THRESHOLD))
        self.spreading_cells = []
        self.last_spreading_cells = []
        

    def move(self):
        if self.age > AGE_THRESHOLD:
            self.die()  
            return
        self.age += 1
        
        # Use optimized collision system to find rats in gas cloud
        victim_ids = self.game.collision_system.get_units_in_cell(
            self.position, use_before=False
        )
        
        for victim_id in victim_ids:
            victim = self.game.get_unit_by_id(victim_id)
            if victim and isinstance(victim, Rat):
                if victim.partial_move > 0.5:
                    victim.gassed += 1
        
        # Check position_before as well
        victim_ids_before = self.game.collision_system.get_units_in_cell(
            self.position, use_before=True
        )
        
        for victim_id in victim_ids_before:
            victim = self.game.get_unit_by_id(victim_id)
            if victim and isinstance(victim, Rat):
                if victim.partial_move < 0.5:
                    victim.gassed += 1
        
        if self.age % self.speed:
            return
        parent = self.game.get_unit_by_id(self.parent_id)
        if (parent) or self.parent_id is None:
            print(f"Gas at {self.position} is spreading")
                # Spread gas to adjacent cells
        
            for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                new_x = self.position[0] + dx
                new_y = self.position[1] + dy
                if not self.game.map.is_wall(new_x, new_y):
                    if not any(isinstance(unit, Gas) for unit in self.game.units.values() if unit.position == (new_x, new_y)):
                        print(f"Spreading gas from {self.position} to ({new_x}, {new_y})")
                        self.game.spawn_unit(Gas, (new_x, new_y), parent_id=self.parent_id if self.parent_id else self.id)
    def collisions(self):
        pass

    def die(self, unit=None, score=None):
        if not unit:
            unit = self
        self.game.units.pop(unit.id)
        
        
    def draw(self):
        image = self.game.assets["BMP_GAS"]
        image_size = self.game.render_engine.get_image_size(image)
        self.rat_image = image
        partial_x, partial_y = 0, 0
        
        x_pos = self.position_before[0] * self.game.cell_size + (self.game.cell_size - image_size[0]) // 2 + partial_x
        y_pos = self.position_before[1] * self.game.cell_size + (self.game.cell_size - image_size[1]) // 2 + partial_y
        self.game.render_engine.draw_image(x_pos, y_pos, image, anchor="nw", tag="unit")
        for cell in self.spreading_cells:
            x_pos = cell[0] * self.game.cell_size + (self.game.cell_size - image_size[0]) // 2 + partial_x
            y_pos = cell[1] * self.game.cell_size + (self.game.cell_size - image_size[1]) // 2 + partial_y
            self.game.render_engine.draw_image(x_pos, y_pos, image, anchor="nw", tag="unit")
