use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use termion::terminal_size;
use std::cmp::Ordering;
use termion::input::TermRead;
use termion::event::Key;

pub enum Event {
    Key(Key),
    Refresh,
}

pub fn setup_events() -> mpsc::Receiver<Event> {
    let (tx,rx) = mpsc::channel();

    let sender = tx.clone();
    thread::spawn(move || {
        let sender = sender;
        let mut size = terminal_size().unwrap(); // handle possible error
        loop {
            let new_size = terminal_size().unwrap(); // handle possible error
            let cmp = size.cmp(&new_size);
            if let Ordering::Less | Ordering::Greater = cmp {
                sender.send(Event::Refresh).unwrap(); // handle possible error
                size = new_size;
            }
            thread::sleep(Duration::from_millis(100));
        }
    });

    thread::spawn(move || {
        let stdin = std::io::stdin();
        for key in stdin.keys() {
            tx.send(Event::Key(key.unwrap())).unwrap(); // handle possible error
        };
    });

    rx
}
