// Copyright 2016 Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

extern crate inotify;
use self::inotify::INotify;
use self::inotify::ffi;
use self::inotify::wrapper::Event;

use std::io::Result;
use std::path::Path;

/// A watcher of a directory for new files.
pub struct Watcher {
    /// The internal inotify watcher.
    ino: INotify,
}

impl Watcher {
    /// Watch a given directory.
    pub fn new(path: &Path) -> Result<Self> {
        let ino = INotify::init()?;
        ino.add_watch(path,
                      ffi::IN_CLOSE_WRITE | ffi::IN_MOVED_TO | ffi::IN_ONLYDIR)?;

        Ok(Watcher {
            ino: ino,
        })
    }

    /// Block until events are returned.
    pub fn events(&mut self) -> Result<Vec<Event>> {
        Ok(self.ino.wait_for_events()?.into())
    }
}
