extern crate rscam;
use fltk::{
    app::App,
    enums::ColorDepth,
    frame::Frame,
    prelude::{GroupExt, WidgetBase, WidgetExt},
    window::Window,
};
use rscam::{Camera, Config};

fn main() {
    let mut camera_open = false;
    let app = App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Hello from rust");
    let mut frame = Frame::default_fill();
    wind.end();
    wind.show();
    // app.run().unwrap();
    // 打开摄像头设备
    let mut camera = Camera::new("/dev/video0").unwrap();

    // 配置摄像头参数
    match camera.start(&Config {
        interval: (1, 30),      // 设置帧率为 30fps
        resolution: (640, 480), // 设置分辨率为 640x480
        format: b"MJPG",        // 设置图像格式为 MJPG
        ..Default::default()
    }) {
        Ok(_) => camera_open = true,
        Err(e) => {
            eprint!("Open Camera Error:{}", e)
        }
    }
    if camera_open {
        loop {
            // 捕获一帧图像
            match camera.capture() {
                Ok(data) => {
                    let img = image::load_from_memory(&data).unwrap();
                    let rgb_data = img.to_rgb8();

                    let fltk_image = fltk::image::RgbImage::new(
                        &rgb_data.as_raw(),
                        rgb_data.width() as i32,
                        rgb_data.height() as i32,
                        ColorDepth::Rgb8,
                    )
                    .unwrap();
                    frame.set_image(Some(fltk_image));
                    frame.redraw();
                }
                Err(e) => {
                    eprintln!("捕获错误: {}", e);
                    continue;
                }
            }
            app.wait();
        }
    }
}