#!/usr/bin/env python3
"""
Go2视频流简单使用示例
展示EZAI库封装后的简洁用法
"""

import os
import cv2

# 设置显示环境
os.environ["DISPLAY"] = ":0"

def simple_video_display():
    """最简单的视频显示示例"""
    print("=== Go2视频流简单显示 ===")
    
    import ezai.go2 as go2
    
    # 1. 初始化（自动检测网络接口）
    print("1. 初始化Go2...")
    robot = go2.Go2()
    robot.init()
    print(f"   使用网络接口: {robot.interface}")
    
    # 2. 获取视频读取器（自动选择最佳方法）
    print("2. 创建视频读取器...")
    read_frame, cleanup = robot.get_video_reader()
    
    if read_frame is None:
        print("   ❌ 无法创建视频读取器")
        return
    
    print("   ✅ 视频读取器创建成功")
    
    # 3. 读取和显示视频
    print("3. 开始显示视频（按q退出）...")
    frame_count = 0
    
    try:
        while True:
            frame = read_frame()
            
            if frame is not None:
                # 显示视频
                cv2.imshow('Go2视频流', frame)
                frame_count += 1
                
                # 每30帧显示一次统计
                if frame_count % 30 == 0:
                    print(f"   已显示 {frame_count} 帧")
                
                # 检查退出
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
            else:
                # 等待下一帧
                pass
                
    finally:
        # 4. 清理资源
        print("4. 清理资源...")
        cleanup()
        cv2.destroyAllWindows()
        print(f"   总共显示了 {frame_count} 帧")

def video_processing_example():
    """视频处理示例"""
    print("\n=== Go2视频处理示例 ===")
    
    import ezai.go2 as go2
    
    # 初始化
    robot = go2.Go2()
    robot.init()
    
    # 获取视频读取器
    read_frame, cleanup = robot.get_video_reader()
    
    if read_frame is None:
        print("❌ 无法创建视频读取器")
        return
    
    print("开始视频处理（按q退出）...")
    
    try:
        while True:
            frame = read_frame()
            
            if frame is not None:
                # 在这里添加你的处理逻辑
                # 例如：边缘检测
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                edges = cv2.Canny(gray, 100, 200)
                
                # 显示原图和处理后的图像
                cv2.imshow('原始视频', frame)
                cv2.imshow('边缘检测', edges)
                
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
                    
    finally:
        cleanup()
        cv2.destroyAllWindows()

def save_video_frames():
    """保存视频帧示例"""
    print("\n=== 保存视频帧示例 ===")
    
    import ezai.go2 as go2
    
    robot = go2.Go2()
    robot.init()
    
    read_frame, cleanup = robot.get_video_reader()
    
    if read_frame is None:
        print("❌ 无法创建视频读取器")
        return
    
    print("开始保存视频帧（每秒保存1帧，按q退出）...")
    
    frame_count = 0
    save_count = 0
    last_save_time = 0
    
    try:
        while True:
            frame = read_frame()
            
            if frame is not None:
                frame_count += 1
                current_time = frame_count * 0.033  # 假设30fps
                
                # 每秒保存一帧
                if current_time - last_save_time >= 1.0:
                    filename = f"go2_frame_{save_count:04d}.jpg"
                    cv2.imwrite(filename, frame)
                    print(f"   保存: {filename}")
                    save_count += 1
                    last_save_time = current_time
                
                cv2.imshow('Go2视频流', frame)
                
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
                    
    finally:
        cleanup()
        cv2.destroyAllWindows()
        print(f"总共保存了 {save_count} 帧图像")

if __name__ == "__main__":
    print("Go2视频流使用示例")
    print("=" * 30)
    print("选择示例:")
    print("1. 简单视频显示")
    print("2. 视频处理示例")
    print("3. 保存视频帧")
    
    try:
        choice = input("请选择 (1/2/3): ").strip()
        
        if choice == "1":
            simple_video_display()
        elif choice == "2":
            video_processing_example()
        elif choice == "3":
            save_video_frames()
        else:
            print("默认运行简单视频显示...")
            simple_video_display()
            
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"程序异常: {e}")