import sys
import sdl2
from PIL import Image
import sdl2.sdlttf
import sdl2.ext


class Main:
    def __init__(self):
        sdl2.ext.init()
        self.size = (800, 600)
        self.window = sdl2.ext.Window("PySDL2 Demo", size=self.size)
        self.window.show()
        self.renderer = sdl2.ext.Renderer(self.window)
        self.factory = sdl2.ext.SpriteFactory(renderer=self.renderer)
        self.fonts = self.generate_fonts("assets/AmaticSC-Regular.ttf")
        self.running = True
        self.assets = self.graphics_load()
    
    def generate_fonts(self,font_file):
        fonts = {}
        for i in range(10, 70, 1):
            fonts.update({i: sdl2.ext.FontManager(font_path=font_file, size=i)})
        return fonts
    
    def draw_text(self, text, font, position, color):
        sprite = self.factory.from_text(text, fontmanager=font, color=color)
        if position == "center":
            sprite.position = (self.size[0] // 2 - sprite.size[0] // 2, self.size[1] // 2 - sprite.size[1] // 2)
        else:
            sprite.position = position
        self.renderer.copy(sprite, dstrect=sprite.position)

    def draw_image(self, sprite, position):
        
        sprite.position = position
        self.renderer.copy(sprite, dstrect=sprite.position)
        
    def load_image(self, path, transparent_color=None):
        image = Image.open(path)
        image = image.resize((image.width * 3, image.height * 3), Image.NEAREST)
        if transparent_color:
            image = image.convert("RGBA")
            datas = image.getdata()
            new_data = []
            for item in datas:
                if item[:3] == transparent_color:
                    new_data.append((255, 255, 255, 0))
                else:
                    new_data.append(item)
            image.putdata(new_data)
        
        return self.factory.from_surface(sdl2.ext.pillow_to_surface(image))
    
    def run(self):
        while self.running:
            events = sdl2.ext.get_events()
            for event in events:
                if event.type == sdl2.SDL_QUIT:
                    self.running = False
                    break
            self.renderer.clear()
            self.draw_text("MatGames Corp.", self.fonts[50], (0, 0), sdl2.ext.Color(255, 255, 255))
            self.draw_image(self.assets["MALE"]["DOWN"], (100, 100))
            self.renderer.present()
        sdl2.ext.quit()
        return 0
    
    def graphics_load(self):
        rat_assets = {}
        for sex in ["MALE", "FEMALE", "BABY"]:
            rat_assets[sex] = {}
            for direction in ["UP", "DOWN", "LEFT", "RIGHT"]:
                rat_assets[sex][direction] = self.load_image(f"assets/Rat/BMP_{sex}_{direction}.png", transparent_color=(128, 128, 128))
        return rat_assets

if __name__ == "__main__":
    sys.exit(Main().run())