extern crate sqa_jack;

use sqa_jack::{JackPort, JackConnection, JackCallbackContext, JackControl, JackHandler, JackResult, PORT_IS_OUTPUT, PORT_IS_INPUT, PORT_IS_PHYSICAL};
use std::thread;
struct Sawtooth {
    out1: JackPort,
    out2: JackPort,
    left_saw: f32,
    right_saw: f32
}
impl JackHandler for Sawtooth {
    fn process(&mut self, ctx: &JackCallbackContext) -> JackControl {
        let out1 = ctx.get_port_buffer(&self.out1).unwrap();
        let out2 = ctx.get_port_buffer(&self.out2).unwrap();
        for (out1, out2) in out1.iter_mut().zip(out2.iter_mut()) {
            *out1 = self.left_saw * 0.2;
            *out2 = self.right_saw * 0.2;
            self.left_saw += 0.01;
            if self.left_saw >= 1.0 { self.left_saw -= 2.0; }
            self.right_saw += 0.03;
            if self.right_saw >= 1.0 { self.right_saw -= 2.0; }
        }
        JackControl::Continue
    }
}
fn run() -> JackResult<()> {
    let mut conn = JackConnection::connect("Very Annoying Sawtooth Generator", None)?;
    let out1 = conn.register_port("output_1", PORT_IS_OUTPUT)?;
    let out2 = conn.register_port("output_2", PORT_IS_OUTPUT)?;
    let data = Sawtooth {
        out1: out1,
        out2: out2,
        left_saw: 0.0,
        right_saw: 0.0
    };
    conn.set_handler(data)?;
    let mut conn = match conn.activate() {
        Ok(nc) => nc,
        Err((_, err)) => return Err(err)
    };
    let ports = conn.get_ports(None, None, Some(PORT_IS_INPUT | PORT_IS_PHYSICAL))?;
    if ports.len() >= 2 {
        conn.connect_ports(&out1, &ports[0])?;
        conn.connect_ports(&out2, &ports[1])?;
    }
    thread::sleep(::std::time::Duration::new(5, 0));
    Ok(())
}
fn main() {
    println!("ADVANCE WARNING: The noise generated by this example can be loud and annoying");
    thread::sleep(::std::time::Duration::new(2, 0));
    println!("{:?}", run());
}
