"""
2D Animation Library Usage Example

2D-Animation-lib 使用示例
"""

import Animation
from camera import Camera
from animation_sprite import AnimationSprite
import pygame
import sys
from pathlib import Path

def _red(text):return f"\033[31m{text}\033[0m"

def get_examples_path(file_name : str):
    cureent_dir = Path(__file__).parent
    examples_path = cureent_dir / "examples" / file_name
    return str(examples_path)

def main():
    print("=" * 50)
    print("""
          2D-Animation-lib Usage Example
          2D-Animation-lib 使用示例
          """)
    print("=" * 50)

    examples_dir = Path(__file__).parent / "examples"
    if not examples_dir.exists():
        print(_red(f"""
        Error: Not found 'examples' folder, please ensure that '2D-Animation-lib' is installed correctly
        错误：未找到 'examples' 文件夹，请确认 '2D-Animation-lib' 是否安装正确
                   
        Path:
        {examples_dir}
        """))
        return
    
    png_files = list(examples_dir.glob("*.png"))
    if not png_files:
        print(_red(f"""
        Error: Not found any '.png' file in 'examples' folder
        错误：'examples' 文件夹下未找到任何 '.png' 文件
                   
        Path:
        {examples_dir}
        """))
        return
    
    print("starting example window...")
    print("=" * 50)

    pygame.init()

    FPS : int = 550

    screen = pygame.display.set_mode((800, 600))
    clock = pygame.time.Clock()

    Animation.add_file_path(examples_dir / "player_walk_1.png", "player_walk", 15)
    Animation.add_file_path(examples_dir / "player1.png", "player", 15)
    Animation.add_file_path(examples_dir / "player_hit_1.png", "player_hit", 15)

    print("\n")
    print(Animation.AnimationStatus("player_walk").get_settings())
    print("\n")
    print(Animation.AnimationStatus("player").get_settings())
    print("\n")
    print(Animation.AnimationStatus("player_hit").get_settings())
    print("\n")

    running : bool = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        screen.fill((255, 255, 255))

        Animation.image_show("player_walk", 100, 100, screen)
        Animation.image_show("player", 300, 100, screen)
        Animation.image_show("player_hit", 500, 100, screen)

        Animation.animation_start("player_walk", 4)
        Animation.animation_start("player", 2, _ = False)
        Animation.animation_start("player_hit", 5)

        pygame.display.flip()
        clock.tick(FPS)
def camera_demo():
    print("=" * 50)
    print("""
          Camera Demo
          摄像机演示
          """)
    print("=" * 50)
    print("""
           Operating Instructions:  
                      ↑↓←→ Control camera movement  
                      Spacebar Zoom in the camera  
                      Shift Zoom out the camera  
                      C Set Sprite direction to 0
           操作方式：
                      ↑↓←→控制相机移动
                      空格放大相机
                      shift 缩小相机
                      C 将 Sprite 方向设为 0
          """)

    screen = pygame.display.set_mode((800, 600))
    Camera.set_screen_center(screen.get_width() // 2, screen.get_height() // 2)

    class Player(AnimationSprite, pygame.sprite.Sprite):
        def __init__(self, x, y, w, h):
            super().__init__(x, y, w, h)
            self.original_image = pygame.Surface((w, h))
            # 画一个带方向的形状，方便观察旋转
            self.original_image.fill((0, 255, 0))
            # 添加一个红色三角形在顶部（不对称特征）
            points = [(w//2, 0), (w//2 - 5, 10), (w//2 + 5, 10)]
            pygame.draw.polygon(self.original_image, (255, 0, 0), points)
            # 画一条红线标记方向
            pygame.draw.line(self.original_image, (255, 0, 0), (w//2, h//2), (w, h//2), 3)
            self.image = self.original_image

    p = Player(Camera.get_screen_center("x"), Camera.get_screen_center("y"), 50, 50)
    p1 = Player(300, 200, 50, 50)
    p2 = Player(200, 100, 50, 50)


    clock = pygame.time.Clock()
    running : bool = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
        pressed_keys = pygame.key.get_pressed()
        if pressed_keys[pygame.K_LEFT]:
            Camera.move(-3, 0)
        elif pressed_keys[pygame.K_RIGHT]:
            Camera.move(3, 0)
        if pressed_keys[pygame.K_UP]:
            Camera.move(0, -3)
        elif pressed_keys[pygame.K_DOWN]:
            Camera.move(0, 3)

        if pressed_keys[pygame.K_SPACE]:
            Camera.add_size(0.1)
        elif pressed_keys[pygame.K_LSHIFT]:
            Camera.add_size(-0.1)

        if pressed_keys[pygame.K_r]:
            Camera.turn_right(10)
        elif pressed_keys[pygame.K_f]:
            Camera.turn_right(-10)

        if pressed_keys[pygame.K_c]:
            Camera.set_direction(0)


        screen.fill((0, 0, 0))

        p.update_animation()
        p.update_position()

        p1.update_animation()
        p1.update_position()

        p2.update_animation()
        p2.update_position()

        screen.blit(p.image, p.rect)
        screen.blit(p1.image, p1.rect)
        screen.blit(p2.image, p2.rect)
        pygame.display.flip()

        clock.tick(60)

    pygame.quit()

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] == "camera":
            camera_demo()
        else:
            main()
    else:
        main()