// 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 std::error;

#[derive(Debug)]
/// Results from an event.
pub enum HandlerResult {
    /// The event was accepted and acted upon.
    Accept,
    /// The event was deferred until a later time for the given reason.
    Defer(String),
    /// The event was rejected for the given reason.
    Reject(String),
    /// The event failed with the given error.
    Fail(Box<error::Error>),
    /// The director should be restarted.
    Restart,
    /// The event was the last one which should be processed.
    Done,
}

impl HandlerResult {
    /// Combine two handler results into one.
    pub fn combine(self, other: Self) -> Self {
        match (self, other) {
            // Acceptance defers to the other.
            (HandlerResult::Accept, next) |
            (next, HandlerResult::Accept) => next,
            // Completion overrides any other status.
            (HandlerResult::Done, _) |
            (_, HandlerResult::Done) => HandlerResult::Done,
            // Once completion is handled, restart takes precedence.
            (HandlerResult::Restart, _) |
            (_, HandlerResult::Restart) => HandlerResult::Restart,
            // Deferring is next.
            (HandlerResult::Defer(left), HandlerResult::Defer(right)) => {
                HandlerResult::Defer(format!("{}\n{}", left, right))
            },
            (defer @ HandlerResult::Defer(_), _) |
            (_, defer @ HandlerResult::Defer(_)) => defer,
            // Failures are handled next.
            (fail @ HandlerResult::Fail(_), _) |
            (_, fail @ HandlerResult::Fail(_)) => fail,
            // All we have left are rejections; combine their messages.
            (HandlerResult::Reject(left), HandlerResult::Reject(right)) => {
                HandlerResult::Reject(format!("{}\n{}", left, right))
            },
        }
    }
}

/// Interface for handling events.
pub trait Handler {
    /// Adds the handler to a director.
    fn add_to_director<'a>(&'a self, director: &mut Director<'a>) -> Result<()>;

    /// The JSON object is passed in and acted upon.
    fn handle(&self, kind: &str, object: &Value) -> Result<HandlerResult>;

    /// The retry limit for a job kind.
    fn retry_limit(&self, _kind: &str) -> usize {
        5
    }

    /// The JSON object which has been retried is passed in and acted upon.
    fn handle_retry(&self, kind: &str, object: &Value, reasons: Vec<String>)
                    -> Result<HandlerResult> {
        if reasons.len() > self.retry_limit(kind) {
            return Ok(HandlerResult::Reject(format!("retry limit ({}) reached for {}",
                                                    reasons.len(),
                                                    kind)));
        }

        self.handle(kind, object)
    }
}
