///|
/// The log of a plugin. The host writes each entry to the logger of the
/// application, with the name of the hosted service.
pub struct PluginLog {
  priv sink : (@logging.Level, String) -> Unit
}

///|
/// Make a log that gives each entry to `sink`.
pub fn PluginLog::new(sink : (@logging.Level, String) -> Unit) -> PluginLog {
  { sink, }
}

///|
/// Write one entry.
pub fn PluginLog::write(
  self : PluginLog,
  level : @logging.Level,
  text : String,
) -> Unit {
  (self.sink)(level, text)
}

///|
/// The two ways in which a MoonBit service refuses a call. Each other error of a
/// service function is a failure with the text of that error.
pub(all) suberror ServiceError {
  /// Refuse the event of this `handle` call. The plugin continues, and its next
  /// step does not change. In each other operation it is a failure.
  EventRejected(String)
  /// The plugin cannot continue.
  ServiceFailed(String)
}

///|
/// A plugin in MoonBit code: its description, and a function that starts it. One
/// value can serve a program that links it, a wasm module and a worker.
pub struct Service {
  priv description : Description
  priv start : (Bytes, PluginLog) -> RunningService raise
}

///|
/// Make a service. `start` gets the settings bytes and the log, and gives the
/// first next step together with the functions for the later calls. Those
/// functions hold the state, so each start has its own state.
pub fn Service::new(
  description : Description,
  start : (Bytes, PluginLog) -> RunningService raise,
) -> Service {
  { description, start, }
}

///|
/// What the service says about itself.
pub fn Service::description(self : Service) -> Description {
  self.description
}

///|
/// A service after its start.
pub struct RunningService {
  priv next : NextStep
  priv handle : (EventName, Bytes) -> (NextStep, Bytes) raise
  priv tick : (Uptime) -> NextStep raise
  priv stop : (StopReason) -> Unit raise
}

///|
/// Give the first next step and the functions of a service that started. With no
/// `handle`, the service rejects each event. With no `tick`, a tick gives
/// `Idle`.
pub fn RunningService::new(
  next : NextStep,
  handle~ : (EventName, Bytes) -> (NextStep, Bytes) raise = (event, _) => {
    raise EventRejected("the plugin has no handler for the event '\{event}'")
  },
  tick~ : (Uptime) -> NextStep raise = _ => Idle,
  stop~ : (StopReason) -> Unit raise = _ => (),
) -> RunningService {
  { next, handle, tick, stop, }
}

///|
/// One instance of a service, on the side of the plugin. It answers the calls of
/// a transport.
pub struct ServiceInstance {
  priv service : Service
  priv log : PluginLog
  priv mut running : RunningService?
}

///|
/// Make an instance that did not start. It writes its log entries to `log`.
pub fn Service::instance(self : Service, log : PluginLog) -> ServiceInstance {
  { service: self, log, running: None, }
}

///|
/// Answer one call. An error of a service function and a request that breaks the
/// contract give a response with that status, so this function does not raise.
pub fn ServiceInstance::respond(
  self : ServiceInstance,
  operation : Operation,
  request : Bytes,
) -> Response {
  let reply : Reply = self.reply(operation, request) catch {
    EventRejected(message) if operation is Handle => Rejected(message)
    EventRejected(message) | ServiceFailed(message) => Failed(message)
    error => Failed(error.to_string())
  }
  reply.encode()
}

///|
fn ServiceInstance::reply(
  self : ServiceInstance,
  operation : Operation,
  request : Bytes,
) -> Reply raise {
  let request = Request::decode(operation, request) catch {
    error => raise ServiceFailed(error.message())
  }
  match (request, self.running) {
    (Describe, _) => Described(self.service.description)
    (Start(settings), None) => {
      let running = (self.service.start)(settings, self.log)
      self.running = Some(running)
      Next(running.next)
    }
    (Start(_), Some(_)) => raise ServiceFailed("the plugin already started")
    (Handle(event, payload), Some(running)) => {
      guard self.service.description.accepts(event) else {
        raise EventRejected("the plugin does not accept the event '\{event}'")
      }
      let (next, reply) = (running.handle)(event, payload)
      Handled(next, reply)
    }
    (Tick(uptime), Some(running)) => Next((running.tick)(uptime))
    (Stop(reason), Some(running)) => {
      self.running = None
      (running.stop)(reason)
      Stopped
    }
    (Handle(_, _) | Tick(_) | Stop(_), None) =>
      raise ServiceFailed("the plugin is not running")
  }
}