///|
/// A call that the app does not do. The text is for people, and a client shows
/// it as it is.
#derive(Eq, Debug)
pub(all) suberror Refusal {
  Refusal(String)
}

///|
/// A call that is not correct. The client has an error, and not the user.
priv suberror CallError {
  /// The app has no command with this name.
  UnknownCommand(String)
  /// The request does not have the shape that the command needs.
  BadRequest(String)
}

///|
/// The state of an instance, and the commands that read and change it. It knows
/// nothing about HTTP or the hub.
priv struct App {
  folder : @core.InstanceFolder
  version : @contracts.Version
  /// Sends an event to each view. The name is the name in the contract.
  publish : (String, Json) -> Unit
  /// Whether a view of this kind is connected.
  has_view : (@app.Surface) -> Bool
  /// Asks for the stop of the server. It returns before the server stops.
  stop : () -> Unit
  now : () -> @app.UnixMillis
  /// A call holds the lock only while it changes the list, writes the file and
  /// sends the event. It never waits for the state of a folder with the lock.
  lock : @async.Mutex
  /// The list that is in the file. Only `App::save` changes it.
  mut projects : @core.ProjectList
  /// The states of the folders. Each folder in `projects` has a known state when
  /// `App::save` sends an event: a call reads the folders that are not known
  /// before it takes the lock, and `add_project` records the new folder.
  states : FolderStates
  /// The project that the next window must show. `show_project` sets it, and
  /// `App::greeting` takes it.
  mut waiting : @core.WaitingProject
  /// True after the first `stop_app`.
  mut stopping : Bool
}

///|
/// An app with a project list that was read from the file of the instance. The
/// folder of the instance must exist, and the task group of `states` must live
/// longer than the last call.
fn App::App(
  folder : @core.InstanceFolder,
  version : @contracts.Version,
  projects : @core.ProjectList,
  states~ : FolderStates,
  publish~ : (String, Json) -> Unit,
  has_view~ : (@app.Surface) -> Bool,
  stop~ : () -> Unit,
  now~ : () -> @app.UnixMillis,
) -> App {
  {
    folder,
    version,
    publish,
    has_view,
    stop,
    now,
    lock: @async.Mutex(),
    projects,
    states,
    waiting: @core.WaitingProject::none(),
    stopping: false,
  }
}

///|
/// A command in the table: JSON in, JSON out.
priv struct Operation {
  name : String
  /// Raises `Refusal` or `BadRequest`.
  run : async (App, Json) -> Json
}

///|
/// Connects a command of the contract to its handler. A handler raises only
/// `Refusal`, so each failure of it has a text for people.
fn[Req : @json.FromJson, Res : ToJson] on(
  command : @proton_contract.Command[Req, Res],
  handler : async (App, Req) -> Res raise Refusal,
) -> Operation {
  {
    name: command.name(),
    run: async fn(app, json) {
      let request : Req = @json.from_json(json) catch {
        JsonDecodeError((path, message)) =>
          match path.to_string() {
            "" => raise BadRequest(message)
            place => raise BadRequest("\{place}: \{message}")
          }
      }
      handler(app, request).to_json()
    },
  }
}

///|
/// Each command of the server, in the order of `@app.server_commands`.
let operations : ReadOnlyArray[Operation] = [
  on(@app.app_info, (app, _) => app.info()),
  on(@app.list_projects, (app, _) => app.list_projects()),
  on(@app.add_project, App::add_project),
  on(@app.open_project, App::open_project),
  on(@app.remove_project, App::remove_project),
  on(@app.show_project, App::show_project),
  on(@app.stop_app, (app, _) => app.stop_app()),
]

///|
/// The names of the commands, in the order of `@app.server_commands`.
fn App::operation_names(_ : App) -> Array[String] {
  operations.iter().map(operation => operation.name).collect()
}

///|
/// Does a command. Raises `Refusal` when the app does not do it, and
/// `CallError` when the name or the request is not correct.
async fn App::call(self : App, name : String, request : Json) -> Json {
  match operations.iter().find_first(operation => operation.name == name) {
    Some(operation) => (operation.run)(self, request)
    None => raise UnknownCommand(name)
  }
}

///|
fn App::info(self : App) -> @app.AppInfo {
  { instance: self.folder.name(), version: self.version, }
}

///|
/// Gives the list as it is after the wait for the states, so the reply is not
/// older than an event that was sent before it.
async fn App::list_projects(self : App) -> Array[@app.Project] noraise {
  self.states.refresh(self.folders())
  self.describe(self.projects)
}

///|
async fn App::add_project(
  self : App,
  request : @app.AddProject,
) -> @app.AddedProject raise Refusal {
  let folder = self.states.find_folder(request.path)
  self.states.refresh(self.folders())
  self.lock.acquire()
  defer self.lock.release()
  let (next, entry, addition) = self.projects.add(folder, (self.now)())
  let projects = match addition {
    New => self.save(next, found=entry.folder)
    AlreadyListed => {
      self.states.record_present(entry.folder)
      self.describe(next)
    }
  }
  { project: project_of(projects, entry.id), addition, }
}

///|
/// Sets the time of the last open. The time is in the list, so this is a change
/// of the list.
///
/// It reads the state of this project again. For the other projects, the event
/// has the last known state.
async fn App::open_project(
  self : App,
  id : @app.ProjectId,
) -> @app.Project raise Refusal {
  let folder = self.folder_of(id)
  let unknown = self
    .folders()
    .filter(other => other != folder && !self.states.is_known(other))
  self.states.refresh([folder, ..unknown])
  self.lock.acquire()
  defer self.lock.release()
  let (next, _) = self.projects.open(id, (self.now)()) catch {
    UnknownProject(id) => raise no_project(id)
  }
  project_of(self.save(next), id)
}

///|
/// Gives the project as it was in the list.
async fn App::remove_project(
  self : App,
  id : @app.ProjectId,
) -> @app.Project raise Refusal {
  self.folder_of(id) |> ignore
  self.states.refresh(self.folders())
  self.lock.acquire()
  defer self.lock.release()
  let (next, _) = self.projects.remove(id) catch {
    UnknownProject(id) => raise no_project(id)
  }
  let removed = project_of(self.describe(self.projects), id)
  self.save(next) |> ignore
  removed
}

///|
/// It does not change the list, so it does not need the lock.
///
/// A start of the desktop app can call this before the page of the window is connected,
/// and the event then comes to no window. So the project waits for the window. A page in
/// a browser needs no such step, because it opens with a link of its own.
async fn App::show_project(
  self : App,
  shown : @app.ShownProject,
) -> @app.Project raise Refusal {
  self.states.refresh([self.folder_of(shown.project)])
  let project = project_of(self.describe(self.projects), shown.project)
  if shown.surface is Desktop && !(self.has_view)(Desktop) {
    self.waiting = WaitingProject(shown.project, (self.now)())
  }
  (self.publish)(@app.project_shown.name(), shown.to_json())
  project
}

///|
/// The event `project_shown` for a view that connects now, if a project waits for it.
/// Only the first window gets it.
fn App::greeting(self : App, surface : @app.Surface) -> @app.ShownProject? {
  guard surface is Desktop else { return None }
  let (project, waiting) = self.waiting.take((self.now)())
  self.waiting = waiting
  project.map(project => { project, surface, })
}

///|
/// Tells the views that the server stops, and asks for the stop. Two views can
/// do this at the same time, and the second call then only gets the reply.
fn App::stop_app(self : App) -> @app.Stopping {
  if !self.stopping {
    self.stopping = true
    (self.publish)(@app.app_stopping.name(), @app.Stopping::{ }.to_json())
    (self.stop)()
  }
  @app.Stopping::{ }
}

///|
/// Writes a new list to the file, makes it the list of the app, and publishes
/// it. The caller holds the lock. `found` is a folder that the call checked.
/// Gives the details of the projects.
///
/// The write is first, so a failed write changes nothing. A cancellation, such
/// as a client that goes away, can stop the call before the write, and then also
/// nothing changes. `write_private` does not stop for a cancellation, and the
/// code after it does not wait for anything: the event has the last known states.
/// So the file, the list and the event always change together, and the events
/// have the order of the changes.
async fn App::save(
  self : App,
  next : @core.ProjectList,
  found? : @core.FolderPath,
) -> Array[@app.Project] raise Refusal {
  let path = self.folder.projects()
  write_private(path, next.to_file_text()) catch {
    error =>
      raise Refusal(
        "The project list is not saved in \{path}: \{reason_of(error)}",
      )
  }
  self.projects = next
  if found is Some(folder) {
    self.states.record_present(folder)
  }
  let projects = self.describe(next)
  (self.publish)(@app.projects_changed.name(), ToJson::to_json(projects))
  projects
}

///|
/// The details of each project, with the last known state of its folder. It does
/// not wait.
fn App::describe(self : App, list : @core.ProjectList) -> Array[@app.Project] {
  list.describe(entry => self.states.state_of(entry.folder))
}

///|
/// The folders of the list.
fn App::folders(self : App) -> Array[@core.FolderPath] {
  self.projects.entries().iter().map(entry => entry.folder).collect()
}

///|
/// The folder of a project in the list.
fn App::folder_of(
  self : App,
  id : @app.ProjectId,
) -> @core.FolderPath raise Refusal {
  match self.projects.entries().iter().find_first(entry => entry.id == id) {
    Some(entry) => entry.folder
    None => raise no_project(id)
  }
}

///|
fn project_of(
  projects : ArrayView[@app.Project],
  id : @app.ProjectId,
) -> @app.Project raise Refusal {
  match projects.iter().find_first(project => project.id == id) {
    Some(project) => project
    None => raise no_project(id)
  }
}

///|
fn no_project(id : @app.ProjectId) -> Refusal {
  Refusal("No project has the ID \{id.to_int()}.")
}

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

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