import pygame
import sys
import os
import json
from pygame.locals import *

# 初始化pygame
pygame.init()
pygame.mixer.init()

# 屏幕设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("高级唐诗三百首")

# 颜色定义
BACKGROUND_COLOR = (245, 245, 220)  # 米白色背景
TEXT_COLOR = (60, 60, 60)
TITLE_COLOR = (139, 69, 19)  # 棕色
HIGHLIGHT_COLOR = (255, 215, 0)  # 金色
BUTTON_COLOR = (70, 130, 180)  # 钢蓝色
BUTTON_HOVER_COLOR = (100, 149, 237)  # 矢车菊蓝

# 字体设置
try:
    title_font = pygame.font.SysFont('simhei', 36)
    normal_font = pygame.font.SysFont('simhei', 20)
    small_font = pygame.font.SysFont('simhei', 16)
    poem_font = pygame.font.SysFont('simhei', 24)
except:
    # 如果没有中文字体，使用默认字体
    title_font = pygame.font.Font(None, 36)
    normal_font = pygame.font.Font(None, 20)
    small_font = pygame.font.Font(None, 16)
    poem_font = pygame.font.Font(None, 24)


class Button:
    def __init__(self, x, y, width, height, text, font=normal_font):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.font = font
        self.hovered = False

    def draw(self, surface):
        color = BUTTON_HOVER_COLOR if self.hovered else BUTTON_COLOR
        pygame.draw.rect(surface, color, self.rect, border_radius=10)
        pygame.draw.rect(surface, (0, 0, 0), self.rect, 2, border_radius=10)

        text_surface = self.font.render(self.text, True, (255, 255, 255))
        text_rect = text_surface.get_rect(center=self.rect.center)
        surface.blit(text_surface, text_rect)

    def check_hover(self, pos):
        self.hovered = self.rect.collidepoint(pos)
        return self.hovered

    def handle_event(self, event):
        if event.type == MOUSEBUTTONDOWN and event.button == 1:
            if self.hovered:
                return True
        return False


class PoetryApp:
    def __init__(self):
        # 加载诗歌数据
        self.poems = self.load_poems()
        self.current_poem_index = 0
        self.search_text = ""
        self.search_results = []
        self.is_searching = False
        self.scroll_offset = 0
        self.max_scroll = 0

        # 创建按钮
        self.prev_button = Button(50, 520, 100, 40, "上一首")
        self.next_button = Button(650, 520, 100, 40, "下一首")
        self.search_button = Button(350, 520, 100, 40, "搜索")
        self.back_button = Button(20, 20, 80, 30, "返回")

        # 背景音乐（可选）
        self.background_music = None

    def load_poems(self):
        """加载诗歌数据"""
        # 这里我们创建一些示例诗歌数据
        # 在实际应用中，你可以从JSON文件或数据库加载
        poems = [
            {
                "title": "静夜思",
                "author": "李白",
                "content": ["床前明月光", "疑是地上霜", "举头望明月", "低头思故乡"]
            },
            {
                "title": "春晓",
                "author": "孟浩然",
                "content": ["春眠不觉晓", "处处闻啼鸟", "夜来风雨声", "花落知多少"]
            },
            {
                "title": "登鹳雀楼",
                "author": "王之涣",
                "content": ["白日依山尽", "黄河入海流", "欲穷千里目", "更上一层楼"]
            },
            {
                "title": "望庐山瀑布",
                "author": "李白",
                "content": ["日照香炉生紫烟", "遥看瀑布挂前川", "飞流直下三千尺", "疑是银河落九天"]
            },
            {
                "title": "江雪",
                "author": "柳宗元",
                "content": ["千山鸟飞绝", "万径人踪灭", "孤舟蓑笠翁", "独钓寒江雪"]
            },
            {
                "title": "相思",
                "author": "王维",
                "content": ["红豆生南国", "春来发几枝", "愿君多采撷", "此物最相思"]
            }
        ]
        return poems

    def search_poems(self, keyword):
        """搜索诗歌"""
        if not keyword.strip():
            self.search_results = []
            self.is_searching = False
            return

        results = []
        keyword = keyword.lower()
        for i, poem in enumerate(self.poems):
            # 在标题、作者或内容中搜索
            if (keyword in poem["title"].lower() or
                keyword in poem["author"].lower() or
                    any(keyword in line.lower() for line in poem["content"])):
                results.append(i)

        self.search_results = results
        self.is_searching = True
        self.current_poem_index = 0 if results else 0

    def get_current_poem(self):
        """获取当前显示的诗歌"""
        if self.is_searching and self.search_results:
            if self.current_poem_index < len(self.search_results):
                return self.poems[self.search_results[self.current_poem_index]]
        elif not self.is_searching and self.current_poem_index < len(self.poems):
            return self.poems[self.current_poem_index]
        return None

    def next_poem(self):
        """显示下一首诗"""
        if self.is_searching:
            if self.current_poem_index < len(self.search_results) - 1:
                self.current_poem_index += 1
        else:
            if self.current_poem_index < len(self.poems) - 1:
                self.current_poem_index += 1

    def prev_poem(self):
        """显示上一首诗"""
        if self.current_poem_index > 0:
            self.current_poem_index -= 1

    def draw_poem(self, surface, poem):
        """绘制诗歌"""
        if not poem:
            return

        # 绘制标题
        title_surface = title_font.render(poem["title"], True, TITLE_COLOR)
        title_rect = title_surface.get_rect(center=(SCREEN_WIDTH//2, 80))
        surface.blit(title_surface, title_rect)

        # 绘制作者
        author_surface = normal_font.render(
            f"—— {poem['author']}", True, TEXT_COLOR)
        author_rect = author_surface.get_rect(center=(SCREEN_WIDTH//2, 120))
        surface.blit(author_surface, author_rect)

        # 绘制诗歌内容
        start_y = 180
        line_height = 40
        for i, line in enumerate(poem["content"]):
            line_surface = poem_font.render(line, True, TEXT_COLOR)
            line_rect = line_surface.get_rect(
                center=(SCREEN_WIDTH//2, start_y + i * line_height))
            surface.blit(line_surface, line_rect)

    def draw_search_interface(self, surface):
        """绘制搜索界面"""
        # 搜索框
        search_rect = pygame.Rect(100, 80, 600, 40)
        pygame.draw.rect(surface, (255, 255, 255), search_rect)
        pygame.draw.rect(surface, TEXT_COLOR, search_rect, 2)

        # 搜索文本
        search_text = self.search_text if self.search_text else "请输入关键词搜索..."
        search_surface = normal_font.render(search_text, True, TEXT_COLOR)
        surface.blit(search_surface, (search_rect.x + 10, search_rect.y + 10))

        # 显示搜索结果数量
        if self.is_searching:
            result_text = f"找到 {len(self.search_results)} 首相关诗歌"
            result_surface = small_font.render(result_text, True, TEXT_COLOR)
            surface.blit(result_surface, (100, 130))

        # 返回按钮
        self.back_button.draw(surface)

    def draw_main_interface(self, surface):
        """绘制主界面"""
        current_poem = self.get_current_poem()
        if current_poem:
            self.draw_poem(surface, current_poem)

        # 绘制导航按钮
        self.prev_button.draw(surface)
        self.next_button.draw(surface)
        self.search_button.draw(surface)

        # 显示当前进度
        if self.is_searching:
            total = len(self.search_results)
            current = self.current_poem_index + 1 if total > 0 else 0
            progress_text = f"第 {current}/{total} 首 (搜索结果)"
        else:
            total = len(self.poems)
            current = self.current_poem_index + 1
            progress_text = f"第 {current}/{total} 首"

        progress_surface = small_font.render(progress_text, True, TEXT_COLOR)
        surface.blit(progress_surface, (SCREEN_WIDTH//2 - 50, 570))

    def handle_events(self, events):
        """处理事件"""
        mouse_pos = pygame.mouse.get_pos()

        for event in events:
            if event.type == QUIT:
                return False

            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    if self.is_searching:
                        self.is_searching = False
                        self.search_text = ""
                    else:
                        return False
                elif self.is_searching and event.key == K_BACKSPACE:
                    self.search_text = self.search_text[:-1]
                elif self.is_searching and event.key != K_RETURN:
                    if len(self.search_text) < 20:  # 限制搜索文本长度
                        self.search_text += event.unicode

            elif event.type == KEYUP:
                if self.is_searching and event.key == K_RETURN:
                    self.search_poems(self.search_text)

            elif event.type == MOUSEBUTTONDOWN:
                if self.is_searching:
                    if self.back_button.handle_event(event):
                        self.is_searching = False
                        self.search_text = ""
                else:
                    if self.prev_button.handle_event(event):
                        self.prev_poem()
                    elif self.next_button.handle_event(event):
                        self.next_poem()
                    elif self.search_button.handle_event(event):
                        self.is_searching = True
                        self.search_text = ""

        # 更新按钮悬停状态
        if self.is_searching:
            self.back_button.check_hover(mouse_pos)
        else:
            self.prev_button.check_hover(mouse_pos)
            self.next_button.check_hover(mouse_pos)
            self.search_button.check_hover(mouse_pos)

        return True


def main():
    app = PoetryApp()
    clock = pygame.time.Clock()

    running = True
    while running:
        events = pygame.event.get()
        running = app.handle_events(events)

        # 填充背景
        screen.fill(BACKGROUND_COLOR)

        # 绘制界面
        if app.is_searching:
            app.draw_search_interface(screen)
        else:
            app.draw_main_interface(screen)

        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()
