///|
/// The rule of a plugin name, a plugin version or an event name that a text
/// breaks.
#derive(Eq, Debug)
pub enum NameRule {
  /// The text is empty.
  Empty
  /// The text has more characters than this limit.
  TooLong(Int32)
  /// The first character is not an ASCII letter.
  FirstNotAsciiLetter
  /// The text holds a character that the type does not permit.
  CharNotAllowed(Char)
}

///|
pub extend NameRule with Eq::{equal, not_equal}

///|
pub extend NameRule with @debug.Debug::{to_repr}

///|
fn NameRule::message(self : NameRule, allowed : String) -> String {
  match self {
    Empty => "the text is empty"
    TooLong(limit) => "the text has more than \{limit} characters"
    FirstNotAsciiLetter => "the text must start with an ASCII letter"
    CharNotAllowed(char) =>
      "the character \{char.to_string().escape()} is not allowed; use \{allowed}"
  }
}

///|
/// A text that is not a valid name or version of the plugin contract. Callers
/// can match the cases, but only the `parse` functions make them.
#derive(Eq, Debug)
pub suberror NameError {
  /// The text `text` is not a plugin name.
  InvalidPluginName(text~ : String, rule~ : NameRule)
  /// The text `text` is not a plugin version.
  InvalidPluginVersion(text~ : String, rule~ : NameRule)
  /// The text `text` is not an event name.
  InvalidEventName(text~ : String, rule~ : NameRule)
}

///|
pub extend NameError with Eq::{equal, not_equal}

///|
pub extend NameError with @debug.Debug::{to_repr}

///|
let name_characters : String = "ASCII letters, digits, '.', '-' and '_'"

///|
/// Text for people that describes the fault.
pub fn NameError::message(self : NameError) -> String {
  match self {
    InvalidPluginName(text~, rule~) =>
      "Invalid plugin name \{text.escape()}: \{rule.message(name_characters)}"
    InvalidPluginVersion(text~, rule~) =>
      "Invalid plugin version \{text.escape()}: \{rule.message("printable ASCII characters and no space")}"
    InvalidEventName(text~, rule~) =>
      "Invalid event name \{text.escape()}: \{rule.message(name_characters)}"
  }
}

///|
/// The largest number of characters of a plugin name and of an event name.
let name_limit : Int32 = 128

///|
/// The largest number of characters of a plugin version.
let version_limit : Int32 = 64

///|
/// The rule of a plugin name or an event name that `text` breaks.
fn broken_name_rule(text : String) -> NameRule? {
  guard text.iter().head() is Some(first) else { return Some(Empty) }
  guard first is ('a'..<='z' | 'A'..<='Z') else {
    return Some(FirstNotAsciiLetter)
  }
  for char in text {
    guard char is ('a'..<='z' | 'A'..<='Z' | '0'..<='9' | '.' | '-' | '_') else {
      return Some(CharNotAllowed(char))
    }
  }
  if text.length() > name_limit {
    Some(TooLong(name_limit))
  } else {
    None
  }
}

///|
/// The name that a plugin gives itself, for example `heartbeat`. It starts with
/// an ASCII letter, holds only ASCII letters, digits, `.`, `-` and `_`, and has
/// at most 128 characters.
#derive(Eq, Hash, Debug)
pub struct PluginName {
  priv text : String
}

///|
pub extend PluginName with Eq::{equal, not_equal}

///|
pub extend PluginName with Hash::{hash, hash_combine}

///|
pub extend PluginName with @debug.Debug::{to_repr}

///|
/// Parse a plugin name.
pub fn PluginName::parse(text : String) -> PluginName raise NameError {
  if broken_name_rule(text) is Some(rule) {
    raise InvalidPluginName(text~, rule~)
  }
  { text, }
}

///|
pub impl Show for PluginName with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend PluginName with Show::{output, to_string}

///|
/// The version that a plugin gives itself, for example `0.1.0`. The host only
/// shows it. It has 1 to 64 printable ASCII characters and no space.
#derive(Eq, Hash, Debug)
pub struct PluginVersion {
  priv text : String
}

///|
pub extend PluginVersion with Eq::{equal, not_equal}

///|
pub extend PluginVersion with Hash::{hash, hash_combine}

///|
pub extend PluginVersion with @debug.Debug::{to_repr}

///|
/// Parse a plugin version.
pub fn PluginVersion::parse(text : String) -> PluginVersion raise NameError {
  guard !text.is_empty() else { raise InvalidPluginVersion(text~, rule=Empty) }
  for char in text {
    guard char is ('!'..<='~') else {
      raise InvalidPluginVersion(text~, rule=CharNotAllowed(char))
    }
  }
  guard text.length() <= version_limit else {
    raise InvalidPluginVersion(text~, rule=TooLong(version_limit))
  }
  { text, }
}

///|
pub impl Show for PluginVersion with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend PluginVersion with Show::{output, to_string}

///|
/// The name of an event that a plugin accepts, for example `heartbeat.count`. It
/// has the same rules as `PluginName`.
#derive(Eq, Hash, Debug)
pub struct EventName {
  priv text : String
}

///|
pub extend EventName with Eq::{equal, not_equal}

///|
pub extend EventName with Hash::{hash, hash_combine}

///|
pub extend EventName with @debug.Debug::{to_repr}

///|
/// Parse an event name.
pub fn EventName::parse(text : String) -> EventName raise NameError {
  if broken_name_rule(text) is Some(rule) {
    raise InvalidEventName(text~, rule~)
  }
  { text, }
}

///|
pub impl Show for EventName with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
pub extend EventName with Show::{output, to_string}