use std::{fs,io,thread,sync};
use rodio;
use graphics::errors::Error;

#[allow(dead_code)]
pub struct Audio {
    thread: thread::JoinHandle<()>,
    sender: sync::mpsc::Sender<String>,
}

impl Audio {
    pub fn init() -> Result<Audio, Error> {
        use self::io::BufReader; // Used for audio file reading

        let endpoint = match rodio::default_endpoint() {
            Some(t) => t,
            None => return Err(
                Error::OtherError("Unable to find default sound device".to_owned())),
        };

        for fmt in endpoint.supported_formats().unwrap() {
            fmt.with_max_samples_rate(16000);
            println!("{:?}", fmt);
        }

        let mut audio_queue = rodio::Sink::new(&endpoint);
        audio_queue.set_volume(0.5);

        let (sender, receiver) = sync::mpsc::channel();
        let thread = thread::spawn(move || {
            while let Ok(v) = receiver.recv() {
                let file = fs::File::open("assets/testing.wav").unwrap();
                let testing_wav = rodio::Decoder::new(BufReader::new(file)).unwrap();
                audio_queue.append(testing_wav);
                println!("should play {}", v);
            }
        });

        Ok(Audio { thread, sender })
    }

    pub fn play(&self, sound: String) {
        self.sender.send(sound).unwrap();
    }
}
