///|
/// A version of the plugin contract that this library supports.
#derive(Eq, Debug)
pub(all) enum ContractVersion {
  V1
}

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

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

///|
/// The number of the version in a description.
pub fn ContractVersion::number(self : ContractVersion) -> Int32 {
  match self {
    V1 => 1
  }
}

///|
/// The version with the number `number`, or `None` when this library does not
/// support it.
pub fn ContractVersion::from_number(number : Int32) -> ContractVersion? {
  match number {
    1 => Some(V1)
    _ => None
  }
}

///|
/// What a plugin says about itself before it starts: the contract version, the
/// name, the version and the events that it accepts. No event name occurs two
/// times.
#derive(Eq, Debug)
pub struct Description {
  priv contract : ContractVersion
  priv name : PluginName
  priv version : PluginVersion
  priv events : ReadOnlyArray[EventName]
}

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

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

///|
/// Make a description of contract version 1.
pub fn Description::new(
  name : PluginName,
  version : PluginVersion,
  events : ArrayView[EventName],
) -> Description raise MessageError {
  for i, event in events {
    guard !events[:i].contains(event) else { raise DuplicateEvent(event) }
  }
  { contract: V1, name, version, events: ReadOnlyArray::from_array(events), }
}

///|
/// The contract version that the plugin uses.
pub fn Description::contract(self : Description) -> ContractVersion {
  self.contract
}

///|
/// The name of the plugin.
pub fn Description::name(self : Description) -> PluginName {
  self.name
}

///|
/// The version of the plugin.
pub fn Description::version(self : Description) -> PluginVersion {
  self.version
}

///|
/// The events that the plugin accepts, in the order of the description.
pub fn Description::events(self : Description) -> ReadOnlyArray[EventName] {
  self.events
}

///|
/// True when the plugin accepts the event `event`.
pub fn Description::accepts(self : Description, event : EventName) -> Bool {
  self.events.contains(event)
}

///|
/// The description as the response bytes of `describe`.
pub fn Description::encode(self : Description) -> Bytes {
  let json : Json = {
    "contract": self.contract.number(),
    "name": self.name.to_string(),
    "version": self.version.to_string(),
    "events": self.events.map(event => event.to_string()),
  }
  @utf8.encode(json.stringify())
}

///|
/// Read the response bytes of `describe`. The decoder ignores fields that it does
/// not know.
pub fn Description::decode(bytes : Bytes) -> Description raise MessageError {
  let text = decode_text(bytes[:], Description)
  let json = @json.parse(text) catch {
    _ => raise InvalidDescription("the text is not valid JSON")
  }
  guard json is Object(fields) else {
    raise InvalidDescription("the JSON value is not an object")
  }
  guard fields.get("contract") is Some(Number(number, ..)) &&
    number.to_int().to_double() == number else {
    raise InvalidDescription("the field \"contract\" must be a whole number")
  }
  guard ContractVersion::from_number(number.to_int()) is Some(contract) else {
    // The rest of another version can have another form, so the name is optional.
    let plugin = if fields.get("name") is Some(String(name)) {
      Some(name)
    } else {
      None
    }
    raise UnsupportedContract(plugin~, found=number.to_int())
  }
  let name = string_field(fields, "name")
  let version = string_field(fields, "version")
  let name = PluginName::parse(name) catch { error => raise InvalidName(error) }
  let version = PluginVersion::parse(version) catch {
    error => raise InvalidName(error)
  }
  guard fields.get("events") is Some(Array(items)) else {
    raise InvalidDescription("the field \"events\" must be an array")
  }
  let events = items.map(item => {
    guard item is String(text) else {
      raise InvalidDescription("each item of \"events\" must be a string")
    }
    EventName::parse(text) catch {
      error => raise InvalidName(error)
    }
  })
  { ..Description::new(name, version, events), contract, }
}

///|
fn string_field(
  fields : Map[String, Json],
  name : String,
) -> String raise MessageError {
  guard fields.get(name) is Some(String(text)) else {
    raise InvalidDescription("the field \{name.escape()} must be a string")
  }
  text
}