///|
/// How long a call waits for the states of folders. A folder on a network share
/// that is off answers after 40 seconds or more on Windows.
let state_limit : Duration = Duration(1000)

///|
/// A read of the state of one folder that started.
priv struct StateRead {
  /// The time of the start, in milliseconds.
  started : Int64
  /// Wakes each call that waits for the read.
  end : @cond_var.Cond
  mut ended : Bool
}

///|
/// The last known state of each folder, and the reads that run.
///
/// The system can need a long time for one folder, and a read that started does
/// not end when its task is cancelled. So no call owns a read. The reads run in a
/// task group, and a call waits for them for a limited time. A folder has one
/// current read, and a later call shares it.
///
/// **End of the server.** The group must live longer than the last call. When
/// its body ends, the group cancels the reads, but `moonbitlang/async` also then
/// waits until the system answers. The event loop does the same, so a normal end
/// of `main` waits too. Thus the owner of the group first completes the stop: it
/// closes the server and removes its files. Then it ends the process with
/// `@env.exit`, which does not wait for a read.
priv struct FolderStates {
  /// Starts a task in the group.
  spawn : (async () -> Unit) -> Unit
  check : async (@core.FolderPath) -> @app.FolderState noraise
  find : async (String) -> @core.FolderPath raise Refusal
  limit : Duration
  /// The keys of both maps are the texts of the paths.
  known : Map[String, @app.FolderState]
  /// The current read of each folder.
  reads : Map[String, StateRead]
}

///|
/// States that are not known yet. `check` reads the state of one folder. `find`
/// reads the path of a folder that exists, from the text of a person.
fn[X] FolderStates::FolderStates(
  group : @async.TaskGroup[X],
  check~ : async (@core.FolderPath) -> @app.FolderState noraise = folder_state,
  find~ : async (String) -> @core.FolderPath raise Refusal = canonical_folder,
  limit~ : Duration = state_limit,
) -> FolderStates {
  {
    spawn: run => group.spawn_bg(run, no_wait=true),
    check,
    find,
    limit,
    known: Map([]),
    reads: Map([]),
  }
}

///|
/// The read of a folder that runs, or a new one.
fn FolderStates::read(
  self : FolderStates,
  folder : @core.FolderPath,
) -> StateRead {
  let key = folder.to_string()
  if self.reads.get(key) is Some(read) {
    return read
  }
  let read = { started: @async.now(), end: @cond_var.Cond(), ended: false, }
  self.reads[key] = read
  (self.spawn)(async fn() {
    defer {
      if self.is_current(key, read) {
        self.reads.remove(key)
      }
      read.ended = true
      read.end.broadcast()
    }
    let state = (self.check)(folder)
    if self.is_current(key, read) {
      self.known[key] = state
    }
  })
  read
}

///|
/// True while no newer state replaced the read. Only the current read of a folder
/// can change the known state.
fn FolderStates::is_current(
  self : FolderStates,
  key : String,
  read : StateRead,
) -> Bool {
  self.reads.get(key) is Some(current) && physical_equal(current, read)
}

///|
/// Reads the states of the folders at the same time, and waits for them.
///
/// A call waits for a read until the read is as old as the limit, so it waits for
/// all of them not longer than the limit. A folder without an answer is then
/// `Missing`. Its read continues, and its answer counts when it comes. Until
/// then, no call waits for this folder again.
async fn FolderStates::refresh(
  self : FolderStates,
  folders : ArrayView[@core.FolderPath],
) -> Unit noraise {
  let reads = folders.map(folder => (folder.to_string(), self.read(folder)))
  // The limit around the loop is for a clock that goes back during the wait.
  try
    @async.with_timeout_opt(self.limit.millis(), () => {
      for item in reads {
        item.1.wait(self.limit)
      }
    })
    |> ignore
  catch {
    // A wait raises nothing.
    _ => ()
  }
  for item in reads {
    if !item.1.ended && self.is_current(item.0, item.1) {
      self.known[item.0] = Missing
    }
  }
}

///|
/// Waits until the read ends or is as old as the limit.
async fn StateRead::wait(self : StateRead, limit : Duration) -> Unit {
  let left = Duration::between(@async.now(), limit.after(self.started)).millis()
  guard left > 0 else { return }
  @async.with_timeout_opt(left.min(limit.millis()), () => {
    // The check is here, because the read can end before this task starts.
    if !self.ended {
      self.end.wait()
    }
  })
  |> ignore
}

///|
/// Reads the path of a folder that exists. The caller waits until the system
/// answers, and a cancellation ends the wait, but not the read.
async fn FolderStates::find_folder(
  self : FolderStates,
  text : String,
) -> @core.FolderPath raise Refusal {
  let answer : Ref[Result[@core.FolderPath, Refusal]?] = Ref(None)
  let ended = Ref(false)
  let end = @cond_var.Cond()
  (self.spawn)(() => {
    defer {
      ended.val = true
      end.broadcast()
    }
    answer.val = Some(Ok((self.find)(text)) catch { refusal => Err(refusal) })
  })
  while !ended.val {
    end.wait()
  }
  match answer.val {
    Some(Ok(folder)) => folder
    Some(Err(refusal)) => raise refusal
    // The group of the reads ended the read.
    None => raise stops_now()
  }
}

///|
/// The refusal of a call after the stop.
fn stops_now() -> Refusal {
  Refusal("Mission Control stops now.")
}

///|
/// Records that a call found the folder. This is newer than the answer of a read
/// that runs, so that answer does not count.
fn FolderStates::record_present(
  self : FolderStates,
  folder : @core.FolderPath,
) -> Unit {
  let key = folder.to_string()
  self.known[key] = Present
  self.reads.remove(key)
}

///|
/// True when the folder has a state from a read or from `record_present`.
fn FolderStates::is_known(
  self : FolderStates,
  folder : @core.FolderPath,
) -> Bool {
  self.known.contains(folder.to_string())
}

///|
/// The last known state. It does not wait. A folder without one is `Missing`.
fn FolderStates::state_of(
  self : FolderStates,
  folder : @core.FolderPath,
) -> @app.FolderState {
  self.known.get_or_default(folder.to_string(), Missing)
}

///|
/// Whether the folder of a project exists at this moment. A file at the path is
/// not the folder. This is the check that the server gives to `FolderStates`.
///
/// It can need a long time, and a cancellation does not end it.
async fn folder_state(folder : @core.FolderPath) -> @app.FolderState noraise {
  try @fs.kind(folder.to_string()) catch {
    // The system says that something is there, or does not say that it is not.
    @os_error.OSError(_) as error if error.is_EACCES() => Present
    // Nothing is there, or the drive or the network share is not there.
    _ => Missing
  } noraise {
    Directory => Present
    _ => Missing
  }
}