import os

class Graphics():
    def load_assets(self):
        print("Loading graphics assets...")
        self.tunnel = self.render_engine.load_image("Rat/BMP_TUNNEL.png", surface=True)
        self.grasses = [self.render_engine.load_image(f"Rat/BMP_1_GRASS_{i+1}.png", surface=True) for i in range(4)]
        self.rat_assets = {}
        self.rat_assets_textures = {}   
        self.bomb_assets = {}
        for sex in ["MALE", "FEMALE", "BABY"]:
            self.rat_assets[sex] = {}
            for direction in ["UP", "DOWN", "LEFT", "RIGHT"]:
                self.rat_assets[sex][direction] = self.render_engine.load_image(f"Rat/BMP_{sex}_{direction}.png", transparent_color=(128, 128, 128))
        for sex in ["MALE", "FEMALE", "BABY"]:
            self.rat_assets_textures[sex] = {}
            for direction in ["UP", "DOWN", "LEFT", "RIGHT"]:
                self.rat_assets_textures[sex][direction] = self.render_engine.load_image(f"Rat/BMP_{sex}_{direction}.png", transparent_color=(128, 128, 128), surface=False)
        for n in range(5):
            self.bomb_assets[n] = self.render_engine.load_image(f"Rat/BMP_BOMB{n}.png", transparent_color=(128, 128, 128))
        self.assets = {}
        for file in os.listdir("assets/Rat"):
            if file.endswith(".png"):
                self.assets[file[:-4]] = self.render_engine.load_image(f"Rat/{file}")
        


    # ==================== RENDERING ====================

    def draw_maze(self):
        if self.background_texture is None:
            print("Generating background texture")
            self.regenerate_background()
        self.render_engine.draw_background(self.background_texture)
    
    def regenerate_background(self):
        """Generate or regenerate the background texture with all permanent elements"""
        texture_tiles = []
        for y, row in enumerate(self.map.matrix):
            for x, cell in enumerate(row):
                variant = x*y % 4
                tile = self.grasses[variant] if cell else self.tunnel
                texture_tiles.append((tile, x*self.cell_size, y*self.cell_size))
        
        # Add blood stains if any exist
        if hasattr(self, 'blood_stains'):
            for position, blood_surface in self.blood_stains.items():
                texture_tiles.append((blood_surface, position[0]*self.cell_size, position[1]*self.cell_size))
        
        self.background_texture = self.render_engine.create_texture(texture_tiles)
    
    def add_blood_stain(self, position):
        """Add a blood stain to the background at the specified position"""
        if not hasattr(self, 'blood_stains'):
            self.blood_stains = {}
        
        # Generate new blood surface
        new_blood_surface = self.render_engine.generate_blood_surface()
        
        if position in self.blood_stains:
            # If there's already a blood stain at this position, combine them
            existing_surface = self.blood_stains[position]
            combined_surface = self.render_engine.combine_blood_surfaces(existing_surface, new_blood_surface)
            
            # Free the old surfaces
            self.render_engine.free_surface(existing_surface)
            self.render_engine.free_surface(new_blood_surface)
            
            self.blood_stains[position] = combined_surface
        else:
            # First blood stain at this position
            self.blood_stains[position] = new_blood_surface
        
        # Regenerate background to include the updated blood stain
        self.background_texture = None
        
    def scroll_cursor(self, x=0, y=0):
        if self.pointer[0] + x > self.map.width or self.pointer[1] + y > self.map.height:
            return
        
        self.pointer = (
            max(1, min(self.map.width-2, self.pointer[0] + x)),
            max(1, min(self.map.height-2, self.pointer[1] + y))
        )
        self.render_engine.scroll_view(self.pointer)