///|
/// An operation of the plugin contract.
#derive(Eq, Debug)
pub(all) enum Operation {
  Describe
  Start
  Handle
  Tick
  Stop
}

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

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

///|
pub impl Show for Operation with fn output(self, logger) {
  logger.write_string(
    match self {
      Describe => "describe"
      Start => "start"
      Handle => "handle"
      Tick => "tick"
      Stop => "stop"
    },
  )
}

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

///|
/// Why the host stops a plugin. The cases are the stop reasons of a host.
#derive(Eq, Debug)
pub(all) enum StopReason {
  /// The command of the host completed.
  Completed
  /// Code in the host asked for the stop.
  Requested
  /// A signal or a console event asked for the stop.
  Signal
  /// The program around the host asked for the stop.
  Embedder
  /// Another service failed its start.
  StartFailed
  /// The command or a service failed.
  Failed
}

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

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

///|
fn StopReason::code(self : StopReason) -> UInt32 {
  match self {
    Completed => 0
    Requested => 1
    Signal => 2
    Embedder => 3
    StartFailed => 4
    Failed => 5
  }
}

///|
fn StopReason::from_code(code : UInt32) -> StopReason raise MessageError {
  match code {
    0 => Completed
    1 => Requested
    2 => Signal
    3 => Embedder
    4 => StartFailed
    5 => Failed
    _ => raise UnknownCode(StopReason, code)
  }
}

///|
/// The time since the plugin started, in whole milliseconds.
#derive(Eq, Compare, Debug)
pub struct Uptime {
  priv millis : UInt64
}

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

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

///|
/// Make an uptime from a count of milliseconds. Each count is valid.
pub fn Uptime::millis(count : UInt64) -> Uptime {
  { millis: count, }
}

///|
/// The count of milliseconds.
pub fn Uptime::to_millis(self : Uptime) -> UInt64 {
  self.millis
}

///|
/// What a plugin asks for after a successful `start`, `handle` or `tick`. The
/// latest next step replaces the earlier one.
#derive(Eq, Debug)
pub(all) enum NextStep {
  /// Make no `tick` call.
  Idle
  /// Call `tick` after this time.
  Wake(@lander_core.TimeLimit)
  /// Make no more calls, and release the plugin.
  Finished
}

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

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

///|
/// One call from the host to a plugin.
#derive(Eq, Debug)
pub(all) enum Request {
  Describe
  /// Start with the settings bytes of the application.
  Start(Bytes)
  /// Handle an event with its payload.
  Handle(EventName, Bytes)
  Tick(Uptime)
  Stop(StopReason)
}

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

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

///|
/// The operation of the request.
pub fn Request::operation(self : Request) -> Operation {
  match self {
    Describe => Describe
    Start(_) => Start
    Handle(_, _) => Handle
    Tick(_) => Tick
    Stop(_) => Stop
  }
}

///|
/// The request bytes. A transport sends them together with the operation.
pub fn Request::encode(self : Request) -> Bytes {
  match self {
    Describe => b""
    Start(settings) => settings
    Handle(event, payload) => {
      let name = @utf8.encode(event.to_string())
      let out = @buffer.Buffer(capacity=4 + name.length() + payload.length())
      out.write_uint_le(name.length().reinterpret_as_uint())
      out.write_bytesview(name[:])
      out.write_bytesview(payload[:])
      out.to_bytes()
    }
    Tick(uptime) => {
      let out = @buffer.Buffer(capacity=8)
      out.write_uint64_le(uptime.millis)
      out.to_bytes()
    }
    Stop(reason) => {
      let out = @buffer.Buffer(capacity=4)
      out.write_uint_le(reason.code())
      out.to_bytes()
    }
  }
}

///|
/// Read the request bytes of `operation`, on the side of the plugin.
pub fn Request::decode(
  operation : Operation,
  bytes : Bytes,
) -> Request raise MessageError {
  match operation {
    Describe => {
      check_length(bytes, 0)
      Describe
    }
    Start => Start(bytes)
    Handle => {
      guard bytes.length() >= 4 else {
        raise WrongLength(expected=4, actual=bytes.length())
      }
      let length = read_u32(bytes, 0)
      guard length <= (bytes.length() - 4).reinterpret_as_uint() else {
        raise NameBeyondEnd(length)
      }
      let end = 4 + length.reinterpret_as_int()
      let text = decode_text(bytes[4:end], EventName)
      let name = EventName::parse(text) catch {
        error => raise InvalidName(error)
      }
      Handle(name, bytes[end:].to_owned())
    }
    Tick => {
      check_length(bytes, 8)
      let low = read_u32(bytes, 0).to_uint64()
      let high = read_u32(bytes, 4).to_uint64()
      Tick({ millis: low | (high << 32), })
    }
    Stop => {
      check_length(bytes, 4)
      Stop(StopReason::from_code(read_u32(bytes, 0)))
    }
  }
}

///|
/// The status of a response.
#derive(Eq, Debug)
pub(all) enum Status {
  Success
  /// The plugin rejected one event.
  Rejected
  /// The plugin failed.
  Failure
}

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

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

///|
/// The number of the status in a transport: 0, 1 or 2.
pub fn Status::code(self : Status) -> UInt32 {
  match self {
    Success => 0
    Rejected => 1
    Failure => 2
  }
}

///|
/// Read the number of a status.
pub fn Status::from_code(code : UInt32) -> Status raise MessageError {
  match code {
    0 => Success
    1 => Rejected
    2 => Failure
    _ => raise UnknownCode(Status, code)
  }
}

///|
/// What a transport gives back for one call: the status and the response bytes.
/// `Reply::decode` reads its meaning.
#derive(Eq, Debug)
pub(all) struct Response {
  status : Status
  body : Bytes
}

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

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

///|
/// The meaning of a response.
#derive(Eq, Debug)
pub(all) enum Reply {
  /// The reply of `describe`.
  Described(Description)
  /// The reply of `start` and `tick`.
  Next(NextStep)
  /// The reply of `handle`, with the reply bytes for the sender.
  Handled(NextStep, Bytes)
  /// The reply of `stop`.
  Stopped
  /// The plugin rejected the event of `handle`, and it continues.
  Rejected(String)
  /// The plugin failed.
  Failed(String)
}

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

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

///|
fn write_next(out : @buffer.Buffer, next : NextStep) -> Unit {
  let (kind, millis) = match next {
    Idle => (0U, 0)
    Wake(after) => (1, after.to_millis())
    Finished => (2, 0)
  }
  out.write_uint_le(kind)
  out.write_uint_le(millis.reinterpret_as_uint())
}

///|
fn read_next(bytes : Bytes) -> NextStep raise MessageError {
  let kind = read_u32(bytes, 0)
  let millis = read_u32(bytes, 4)
  match (kind, millis) {
    (0, 0) => Idle
    (1, _) =>
      // A count above the largest time limit is negative as an `Int`, or too large.
      Wake(@lander_core.TimeLimit::millis(millis.reinterpret_as_int())) catch {
        _ => raise InvalidWakeTime(millis)
      }
    (2, 0) => Finished
    (0 | 2, _) => raise InvalidWakeTime(millis)
    _ => raise UnknownCode(NextStep, kind)
  }
}

///|
/// The reply as a response, on the side of the plugin.
pub fn Reply::encode(self : Reply) -> Response {
  match self {
    Described(description) => { status: Success, body: description.encode(), }
    Next(next) => Reply::Handled(next, b"").encode()
    Handled(next, reply) => {
      let out = @buffer.Buffer(capacity=8 + reply.length())
      write_next(out, next)
      out.write_bytesview(reply[:])
      { status: Success, body: out.to_bytes(), }
    }
    Stopped => { status: Success, body: b"", }
    Rejected(message) => { status: Rejected, body: @utf8.encode(message), }
    Failed(message) => { status: Failure, body: @utf8.encode(message), }
  }
}

///|
/// Read the response of `operation`. Only `handle` can reject; for each other
/// operation, the status `Rejected` is a failure. A message that is not valid
/// UTF-8 gets replacement characters, so the text is not lost.
pub fn Reply::decode(
  operation : Operation,
  response : Response,
) -> Reply raise MessageError {
  let body = response.body
  match (response.status, operation) {
    (Rejected, Handle) => Rejected(@utf8.decode_lossy(body[:]))
    (Rejected | Failure, _) => Failed(@utf8.decode_lossy(body[:]))
    (Success, Describe) => Described(Description::decode(body))
    (Success, Start | Tick) => {
      check_length(body, 8)
      Next(read_next(body))
    }
    (Success, Handle) => {
      guard body.length() >= 8 else {
        raise WrongLength(expected=8, actual=body.length())
      }
      Handled(read_next(body), body[8:].to_owned())
    }
    (Success, Stop) => {
      check_length(body, 0)
      Stopped
    }
  }
}

///|
/// The part of a message that holds an invalid value.
#derive(Eq, Debug)
pub enum MessagePart {
  Description
  EventName
  NextStep
  StopReason
  Status
}

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

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

///|
fn MessagePart::text(self : MessagePart) -> String {
  match self {
    Description => "description"
    EventName => "event name"
    NextStep => "next step"
    StopReason => "stop reason"
    Status => "status"
  }
}

///|
/// A message that breaks the plugin contract. Callers can match the cases, but
/// only the functions of this package make them.
#derive(Eq, Debug)
pub suberror MessageError {
  /// The part is not valid UTF-8.
  InvalidText(MessagePart)
  /// The description has a wrong form, for the given reason.
  InvalidDescription(String)
  /// The plugin `plugin` uses the contract version `found`.
  UnsupportedContract(plugin~ : String?, found~ : Int32)
  /// The description or the event holds an invalid name or version.
  InvalidName(NameError)
  /// The description holds an event name two times.
  DuplicateEvent(EventName)
  /// The message must have `expected` bytes, or at least that many when a payload
  /// can follow.
  WrongLength(expected~ : Int32, actual~ : Int32)
  /// The event name has more bytes than the message.
  NameBeyondEnd(UInt32)
  /// The part has a number with no meaning.
  UnknownCode(MessagePart, UInt32)
  /// The wake time in milliseconds does not agree with the kind of the next step:
  /// "wake" needs a time above 0 and not above the largest `TimeLimit`, and the
  /// other kinds need 0.
  InvalidWakeTime(UInt32)
}

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

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

///|
/// Text for people that describes the fault.
pub fn MessageError::message(self : MessageError) -> String {
  match self {
    InvalidText(part) => "the \{part.text()} is not valid UTF-8"
    InvalidDescription(reason) => "the description is not valid: \{reason}"
    UnsupportedContract(plugin~, found~) => {
      let plugin = match plugin {
        Some(name) => "the plugin \{name.escape()}"
        None => "the plugin"
      }
      "\{plugin} uses contract version \{found}; this host supports only version \{ContractVersion::V1.number()}"
    }
    InvalidName(error) => error.message()
    DuplicateEvent(event) =>
      "the description holds the event name '\{event}' two times"
    WrongLength(expected~, actual~) =>
      "the message has \{actual} bytes; expected \{expected}"
    NameBeyondEnd(length) =>
      "the event name of \{length} bytes does not fit into the message"
    UnknownCode(part, code) => "the \{part.text()} \{code} is not known"
    InvalidWakeTime(millis) =>
      "the wake time \{millis} ms is not valid for this next step"
  }
}

///|
fn check_length(bytes : Bytes, expected : Int32) -> Unit raise MessageError {
  guard bytes.length() == expected else {
    raise WrongLength(expected~, actual=bytes.length())
  }
}

///|
fn decode_text(
  bytes : BytesView,
  part : MessagePart,
) -> String raise MessageError {
  @utf8.decode(bytes) catch {
    _ => raise InvalidText(part)
  }
}

///|
/// The little-endian number at `at`. The caller checked the length.
fn read_u32(bytes : Bytes, at : Int32) -> UInt32 {
  bytes[at].to_uint() |
  (bytes[at + 1].to_uint() << 8) |
  (bytes[at + 2].to_uint() << 16) |
  (bytes[at + 3].to_uint() << 24)
}