use gstreamer::{format::ClockTime, prelude::*, MessageView};
use std::{thread, time, time::Duration};

fn main() {
    gstreamer::init().unwrap();

    let uri = "file:///home/savanni/Music/Lindsey%20Stirling/Artemis/01%20-%20Underground.mp3.mp3";
    let pipeline = gstreamer::parse_launch(&format!("playbin uri={}", uri)).unwrap();
    pipeline.set_state(gstreamer::State::Playing).unwrap();

    let message_handler = {
        let pipeline = pipeline.clone();
        thread::spawn(move || {
            let bus = pipeline.bus().unwrap();
            for msg in bus.iter_timed(gstreamer::ClockTime::NONE) {
                match msg.view() {
                    MessageView::Eos(_) => (),
                    MessageView::Error(err) => {
                        println!(
                            "Error from {:?}: {} ({:?})",
                            err.src().map(|s| s.path_string()),
                            err.error(),
                            err.debug()
                        );
                    }
                    msg => println!("{:?}", msg),
                }
            }
        })
    };

    let query_handler = {
        let pipeline = pipeline.clone();
        thread::spawn(move || loop {
            let position: Option<ClockTime> = pipeline.query_position();
            let duration: Option<ClockTime> = pipeline.query_duration();
            println!("Position {:?} {:?}", position, duration);
            thread::sleep(Duration::from_millis(100));
        })
    };

    message_handler.join();
    query_handler.join();

    pipeline.set_state(gstreamer::State::Null).unwrap();
}
