// 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 serde_json;
use self::serde_json::Value;

use super::director::Director;
use super::error::Result;
use super::handler::{Handler, HandlerResult};

#[derive(Debug, Clone, Copy, Default)]
/// A watchdog for the director.
///
/// This handles `watchdog:restart` and `watchdog:exit` job kinds to make restarting and exiting
/// the director easier.
pub struct DirectorWatchdog;

impl Handler for DirectorWatchdog {
    fn add_to_director<'a>(&'a self, director: &mut Director<'a>) -> Result<()> {
        try!(director.add_handler("watchdog:restart", self));
        try!(director.add_handler("watchdog:exit", self));

        Ok(())
    }

    fn handle(&self, kind: &str, _: &Value) -> Result<HandlerResult> {
        Ok(match kind {
            "watchdog:restart" => HandlerResult::Restart,
            "watchdog:exit" => HandlerResult::Done,
            _ => HandlerResult::Reject(format!("watchdog received an unhandled {} job", kind)),
        })
    }
}
