import pygame
import sys
from datetime import datetime, timedelta
import os

# 初始化pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame定时器 - 中文版")

# 颜色定义
BACKGROUND = (25, 25, 40)
TIMER_BG = (40, 40, 60)
TIMER_TEXT = (100, 200, 255)
BUTTON_NORMAL = (70, 130, 180)
BUTTON_HOVER = (100, 160, 210)
BUTTON_TEXT = (240, 240, 240)
WARNING_COLOR = (255, 100, 100)
SUCCESS_COLOR = (100, 255, 150)

# 尝试加载中文字体


def load_font(font_path, size):
    try:
        if os.path.exists(font_path):
            return pygame.font.Font(font_path, size)
        else:
            print(f"字体文件不存在: {font_path}")
            return pygame.font.Font(None, size)
    except Exception as e:
        print(f"字体加载失败: {e}")
        return pygame.font.Font(None, size)


# 尝试加载常见的中文字体
font_paths = [
    "C:/Windows/Fonts/simsun.ttc",           # 宋体
    "C:/Windows/Fonts/simhei.ttf",           # 黑体
    "C:/Windows/Fonts/msyh.ttc",             # 微软雅黑
    "C:/Windows/Fonts/simkai.ttf",           # 楷体
    "simsun.ttc",                            # 当前目录下的字体
    "simhei.ttf",                            # 当前目录下的字体
    None                                      # 最后尝试默认字体
]

# 加载字体
font_large = None
font_medium = None
font_small = None

for font_path in font_paths:
    try:
        if font_path is None:
            font_large = pygame.font.Font(None, 120)
            font_medium = pygame.font.Font(None, 60)
            font_small = pygame.font.Font(None, 40)
            print("使用默认字体")
            break
        elif os.path.exists(font_path):
            font_large = pygame.font.Font(font_path, 120)
            font_medium = pygame.font.Font(font_path, 60)
            font_small = pygame.font.Font(font_path, 40)
            print(f"使用字体: {font_path}")
            break
    except Exception as e:
        print(f"加载字体 {font_path} 失败: {e}")
        continue

# 如果字体加载失败，使用默认字体
if font_large is None:
    font_large = pygame.font.Font(None, 120)
    font_medium = pygame.font.Font(None, 60)
    font_small = pygame.font.Font(None, 40)
    print("使用默认字体作为后备")

# 定时器状态


class Timer:
    def __init__(self):
        self.is_running = False
        self.start_time = None
        self.duration = timedelta(minutes=1)  # 默认1分钟
        self.remaining_time = self.duration
        self.is_completed = False
        self.last_beep = None

    def start(self):
        if not self.is_running:
            self.is_running = True
            self.start_time = datetime.now()
            self.is_completed = False

    def pause(self):
        if self.is_running:
            self.is_running = False
            self.update_remaining()

    def reset(self):
        self.is_running = False
        self.remaining_time = self.duration
        self.is_completed = False

    def update(self):
        if self.is_running and not self.is_completed:
            elapsed = datetime.now() - self.start_time
            remaining = self.duration - elapsed

            if remaining.total_seconds() <= 0:
                self.remaining_time = timedelta(0)
                self.is_completed = True
                self.is_running = False
            else:
                self.remaining_time = remaining

    def update_remaining(self):
        if self.is_running and self.start_time:
            elapsed = datetime.now() - self.start_time
            self.remaining_time = self.duration - elapsed

    def set_duration(self, minutes, seconds=0):
        self.duration = timedelta(minutes=minutes, seconds=seconds)
        if not self.is_running:
            self.remaining_time = self.duration
        self.is_completed = False

# 按钮类


class Button:
    def __init__(self, x, y, width, height, text, action):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.action = action
        self.is_hovered = False

    def draw(self, surface):
        color = BUTTON_HOVER if self.is_hovered else BUTTON_NORMAL
        pygame.draw.rect(surface, color, self.rect, border_radius=15)
        pygame.draw.rect(surface, (255, 255, 255),
                         self.rect, 3, border_radius=15)

        # 渲染文本，确保使用正确的字体
        try:
            text_surf = font_small.render(self.text, True, BUTTON_TEXT)
        except:
            # 如果字体渲染失败，尝试使用默认字体
            fallback_font = pygame.font.Font(None, 40)
            text_surf = fallback_font.render(self.text, True, BUTTON_TEXT)

        text_rect = text_surf.get_rect(center=self.rect.center)
        surface.blit(text_surf, text_rect)

    def check_hover(self, pos):
        self.is_hovered = self.rect.collidepoint(pos)
        return self.is_hovered

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.rect.collidepoint(event.pos):
                return self.action
        return None


# 创建定时器实例
timer = Timer()

# 创建按钮
buttons = [
    Button(WIDTH//2 - 200, HEIGHT - 120, 120, 50, "开始", "start"),
    Button(WIDTH//2 - 60, HEIGHT - 120, 120, 50, "暂停", "pause"),
    Button(WIDTH//2 + 80, HEIGHT - 120, 120, 50, "重置", "reset")
]

# 主循环
clock = pygame.time.Clock()
running = True

# 用于显示字体状态的文本
font_status = "使用默认字体" if font_paths[
    -1] is None else f"使用字体: {[p for p in font_paths if os.path.exists(p)][0]}"

while running:
    mouse_pos = pygame.mouse.get_pos()

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 处理按钮点击
        for button in buttons:
            action = button.handle_event(event)
            if action == "start":
                timer.start()
            elif action == "pause":
                timer.pause()
            elif action == "reset":
                timer.reset()

        # 键盘控制
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                if timer.is_running:
                    timer.pause()
                else:
                    timer.start()
            elif event.key == pygame.K_r:
                timer.reset()
            elif event.key == pygame.K_1:
                timer.set_duration(1)
                timer.reset()
            elif event.key == pygame.K_3:
                timer.set_duration(3)
                timer.reset()
            elif event.key == pygame.K_5:
                timer.set_duration(5)
                timer.reset()
            elif event.key == pygame.K_0:
                timer.set_duration(0, 10)  # 10秒
                timer.reset()

    # 更新定时器
    timer.update()

    # 更新按钮悬停状态
    for button in buttons:
        button.check_hover(mouse_pos)

    # 绘制界面
    screen.fill(BACKGROUND)

    # 绘制标题
    title = font_medium.render("Pygame定时器", True, (255, 255, 255))
    screen.blit(title, (WIDTH//2 - title.get_width()//2, 30))

    # 绘制定时器显示区域
    timer_bg = pygame.Rect(WIDTH//2 - 200, HEIGHT//2 - 150, 400, 200)
    pygame.draw.rect(screen, TIMER_BG, timer_bg, border_radius=20)
    pygame.draw.rect(screen, (100, 100, 150), timer_bg, 5, border_radius=20)

    # 格式化显示时间
    minutes = timer.remaining_time.seconds // 60
    seconds = timer.remaining_time.seconds % 60
    time_str = f"{minutes:02d}:{seconds:02d}"

    # 根据时间状态选择颜色
    if timer.is_completed:
        time_color = SUCCESS_COLOR
        status_text = "时间到！"
    elif timer.is_running:
        time_color = TIMER_TEXT
        status_text = "进行中..."
    else:
        time_color = (180, 180, 200)
        status_text = "已暂停"

    # 绘制时间
    time_display = font_large.render(time_str, True, time_color)
    screen.blit(time_display, (WIDTH//2 -
                time_display.get_width()//2, HEIGHT//2 - 100))

    # 绘制状态文本
    status = font_small.render(status_text, True, time_color)
    screen.blit(status, (WIDTH//2 - status.get_width()//2, HEIGHT//2 - 10))

    # 绘制控制按钮
    for button in buttons:
        button.draw(screen)

    # 绘制说明文本
    instruction1 = font_small.render(
        "点击按钮控制定时器，时间到会有提示", True, (200, 200, 200))
    screen.blit(instruction1, (WIDTH//2 - instruction1.get_width()//2, 380))

    instruction2 = font_small.render(
        "快捷键: 空格=开始/暂停, R=重置", True, (200, 200, 200))
    screen.blit(instruction2, (WIDTH//2 - instruction2.get_width()//2, 420))

    instruction3 = font_small.render(
        "数字键1/3/5: 设置为1/3/5分钟, 0: 10秒", True, (200, 200, 200))
    screen.blit(instruction3, (WIDTH//2 - instruction3.get_width()//2, 460))

    # 绘制当前时间
    current_time = datetime.now().strftime("%H:%M:%S")
    clock_text = font_small.render(
        f"当前时间: {current_time}", True, (150, 200, 150))
    screen.blit(clock_text, (WIDTH - clock_text.get_width() - 20, 20))

    # 绘制字体状态
    font_info = font_small.render(
        f"字体状态: {font_status}", True, (150, 150, 150))
    screen.blit(font_info, (20, 20))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()
sys.exit()
