// The connection of the UI to the server: Proton's client over a SignalR hub, and
// the loop that connects again. No other file of the UI names SignalR (design CON-1).

///|
/// What the UI knows about its connection to the server.
#derive(Eq, Debug)
pub(all) enum ConnectionState {
  /// The first try is not complete.
  Connecting
  /// Calls and events work. The UI reads its data again after each change to this
  /// state, because the server does not repeat events.
  Connected
  /// The connection ended, or a try failed. The loop tries again.
  Reconnecting
  /// The server started again and does not know the session. The loop ended.
  Restarted
  /// A user stopped Mission Control. The loop ended.
  Stopped
}

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

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

///|
/// What the server says about the session of the view.
#derive(Eq, Debug)
pub(all) enum SessionCheck {
  /// The server knows the session.
  Valid
  /// The server refuses the session, because it started again.
  Invalid
  /// The server gave no answer, so nothing is known about the session.
  NoAnswer
}

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

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

///|
/// The meaning of the HTTP status of `GET /session`. Another status does not come
/// from Mission Control, so it is no answer.
fn SessionCheck::of_status(status : Int32) -> SessionCheck {
  match status {
    204 => Valid
    403 => Invalid
    _ => NoAnswer
  }
}

///|
/// The rule of a view key that a text breaks. An error never has the text, because
/// the text can be almost a key.
#derive(Eq, Debug)
pub(all) suberror ViewKeyError {
  /// The text has no characters.
  Empty
  /// A character is not a letter from `a` to `z` or `A` to `Z`, a digit, `-` or `_`.
  NotUrlSafe
  /// The text has more characters than an access token of a hub can have.
  TooLong
}

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

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

///|
/// The key that the server gave this view with its session. The page sends it with
/// the cookie in each request for the hub and for the session. Debug text never shows
/// it, and no function gives its text.
#derive(Eq, Debug)
struct ViewKey {
  token : @signalr.AccessToken
}

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

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

///|
/// Parses the text of a view key, which is URL-safe base64 without padding.
pub fn ViewKey::ViewKey(text : String) -> ViewKey raise ViewKeyError {
  guard !text.is_empty() else { raise Empty }
  for char in text {
    guard char is ('a'..<='z' | 'A'..<='Z' | '0'..<='9' | '-' | '_') else {
      raise NotUrlSafe
    }
  }
  // The length is the only other rule of an access token.
  let token = @signalr.AccessToken::parse(text) catch { _ => raise TooLong }
  { token, }
}

///|
/// The time that the server has to answer a session check, in milliseconds.
let session_check_limit : Int32 = 5000

///|
/// Asks the server for the session of this view. `url` is the complete URL of
/// `/session`, for example `http://127.0.0.1:3090/session`. The browser adds the
/// cookie. A failed request, also because of a wrong URL, is `NoAnswer`.
pub async fn check_session(url : String, key : ViewKey) -> SessionCheck {
  let status = @async.with_timeout_opt(session_check_limit, () => {
    let (response, _) = @http.get(url, headers={
      "Authorization": "Bearer \{key.token.expose()}",
    })
    response.code
  }) catch {
    _ => None
  }
  match status {
    Some(status) => SessionCheck::of_status(status)
    None => NoAnswer
  }
}

///|
/// The time before a try, in milliseconds. `attempt` is the number of tries that
/// failed since the last long connection: the UI tries at once, after 1, 2 and 5
/// seconds, and then each 5 seconds.
pub fn retry_delay(attempt : Int32) -> Int32 {
  match attempt {
    0 => 0
    1 => 1000
    2 => 2000
    _ => 5000
  }
}

///|
/// How long a connection was open.
priv enum OpenTime {
  /// Less than 5 seconds. The try that made the connection is a failed try. Else a
  /// server that accepts and drops would get tries with no delay.
  Short
  /// 5 seconds or more. The tries before it do not count now.
  Long
}

///|
/// The kind of a time in milliseconds.
fn OpenTime::of_milliseconds(time : Int64) -> OpenTime {
  if time < 5000 {
    Short
  } else {
    Long
  }
}

///|
/// What happens to a connection.
priv enum ConnectionEvent {
  /// A try made a connection.
  Opened
  /// An open connection ended. After a `Short` one comes a `TryFailed`.
  Lost(OpenTime)
  /// A try made no connection or a short one, and this is what the server then said
  /// about the session.
  TryFailed(SessionCheck)
  /// The UI knows that a user stopped Mission Control.
  Ended
}

///|
/// The state of the loop.
priv struct Progress {
  state : ConnectionState
  /// The number of tries that failed since the last long connection.
  failed_tries : Int32
}

///|
/// The loop ends in these states, and they do not change.
fn Progress::is_final(self : Progress) -> Bool {
  self.state is (Restarted | Stopped)
}

///|
/// The state after an event.
fn next(progress : Progress, event : ConnectionEvent) -> Progress {
  guard !progress.is_final() else { progress }
  match event {
    Opened => { ..progress, state: Connected, }
    Lost(Short) => { ..progress, state: Reconnecting, }
    Lost(Long) => { state: Reconnecting, failed_tries: 0, }
    TryFailed(Valid | NoAnswer) =>
      { state: Reconnecting, failed_tries: progress.failed_tries + 1, }
    TryFailed(Invalid) => { ..progress, state: Restarted, }
    Ended => { ..progress, state: Stopped, }
  }
}

///|
/// One open connection. A test gives one in memory. Requests, replies and event
/// payloads are JSON text, as in Proton's client.
priv struct Line {
  /// Calls a method of the hub, and gives its reply.
  call : async (@signalr.MethodName, String) -> String
  /// Sets the one handler of an event. Each event gives its payload.
  listen : (@signalr.MethodName, (String) -> Unit) -> Unit
  /// Returns when the connection ends.
  lost : async () -> Unit
}

///|
/// The open connection, and the group of the calls that use it.
priv struct OpenLine {
  line : Line
  calls : @async.TaskGroup
}

///|
/// One subscription of the UI.
priv struct Listener {
  receive : (String) -> Unit
}

///|
/// The connection of the UI. One value lives as long as the page.
pub struct Connection {
  /// Calls the server and gets its events. A call with no open connection fails at
  /// once with `TransportFailure`. A subscription continues on each new connection.
  client : @proton_client.Client
  /// Connects, and connects again after a loss, until the state is `Restarted` or
  /// `Stopped`. It gives the first state and then each change. Call it one time, in
  /// a task of the async runtime. It raises an error only for a wrong hub URL.
  run : async ((ConnectionState) -> Unit) -> Unit
  /// Tells the loop that a user stopped Mission Control. The state is `Stopped` when
  /// the function returns, and a call that waits then fails.
  stopped : () -> Unit
}

///|
/// The connection to the hub at `url`, for example `http://127.0.0.1:3090/hub`, with
/// the key of the view. `session` asks the server for the session after each failed
/// try; see `check_session`. A page with no key uses `Connection::without_key`.
///
/// The cause of each failure goes to the console of the browser, without the key.
pub fn Connection::to_hub(
  url : String,
  key : ViewKey,
  session : async () -> SessionCheck,
) -> Connection {
  // An error text can come from the server, so it is not safe to show as it is.
  let log = (text : String) => {
    console_warn(text.replace_all(old=key.token.expose(), new="[REDACTED]"))
  }
  let open = hub_at(url, key, log) catch {
    error => {
      let fail : async () -> Unit = () => raise error
      return { ..Connection::over(_ => fail(), session), run: _ => fail(), }
    }
  }
  Connection::over(open, session, log~)
}

///|
/// The connection of a page that has no view key. The server refuses such a page, so
/// the state is `Restarted` from the start: `run` gives it and ends, with no request.
/// Each call fails with `TransportFailure`.
pub fn Connection::without_key() -> Connection {
  Connection::over(_ => (), () => Invalid, first=Restarted)
}

///|
/// Writes a warning to the console of the browser.
extern "js" fn console_warn(text : String) -> Unit =
  #| (text) => console.warn(text)

///|
/// The time since the page started, in milliseconds. Nobody can set it back.
extern "js" fn page_milliseconds() -> Double =
  #| () => performance.now()

///|
/// The time since the page started, in whole milliseconds.
fn page_time() -> Int64 {
  page_milliseconds().to_int64()
}

///|
/// The connection over `open`, which connects, runs a function with the open
/// connection, and raises an error when it cannot connect. `first` is the first
/// state. `sleep` waits, and `now` gives the time, both in milliseconds. `log` gets
/// the cause of each failure.
fn Connection::over(
  open : async (async (Line) -> Unit) -> Unit,
  session : async () -> SessionCheck,
  first~ : ConnectionState = Connecting,
  sleep~ : async (Int32) -> Unit = delay => @async.sleep(delay),
  now~ : () -> Int64 = page_time,
  log~ : (String) -> Unit = console_warn,
) -> Connection {
  let progress : Ref[Progress] = Ref({ state: first, failed_tries: 0, })
  let report : Ref[(ConnectionState) -> Unit] = Ref(_ => ())
  let current : Ref[OpenLine?] = Ref(None)
  let end = @async.Cond()
  // A hub connection keeps one handler for each event and forgets it at its end, so
  // the listeners live here.
  let listeners : Map[@signalr.MethodName, Array[Listener]] = Map([])
  let step = (event : ConnectionEvent) => {
    let before = progress.val.state
    progress.val = next(progress.val, event)
    if progress.val.state != before {
      (report.val)(progress.val.state)
    }
  }
  let listen = (line : Line, name : @signalr.MethodName) => {
    (line.listen)(name, payload => {
      for listener in listeners.get(name).unwrap_or([]) {
        (listener.receive)(payload)
      }
    })
  }
  let listen_all = (line : Line) => {
    for name in listeners.keys() {
      listen(line, name)
    }
  }
  // Uses an open connection until it ends, and then writes down how long it was open.
  let use_line : async (Line, Ref[OpenTime?]) -> Unit = (line, open_time) => {
    // The hub drops an event that has no handler, so this comes before each wait.
    listen_all(line)
    @async.with_task_group(calls => {
      guard !progress.val.is_final() else {  }
      current.val = Some({ line, calls, })
      defer {
        current.val = None
      }
      // The start of this group is a wait, and a listener can come in that time.
      listen_all(line)
      let opened = now()
      step(Opened)
      (line.lost)()
      current.val = None
      let time = OpenTime::of_milliseconds(now() - opened)
      open_time.val = Some(time)
      // The hub client closes the old connection after this, which takes time.
      step(Lost(time))
      calls.return_immediately()
    })
  }
  let connect : async () -> Unit = () => {
    while !progress.val.is_final() {
      sleep(retry_delay(progress.val.failed_tries))
      let open_time : Ref[OpenTime?] = Ref(None)
      open_in_time(open, sleep, line => use_line(line, open_time)) catch {
        error => log("No connection to Mission Control: \{error}")
      }
      if !(open_time.val is Some(Long)) {
        step(TryFailed(session() catch { _ => NoAnswer }))
      }
    }
    end.signal()
  }
  {
    client: @proton_client.Client(
      invoke=(route, request, success, failure) => {
        guard current.val is Some({ line, calls, }) else {
          failure(
            TransportFailure(message="Mission Control has no connection now"),
          )
          return () => ()
        }
        let task = calls.spawn(no_wait=true, allow_failure=true, () => {
          let reply : Ref[Result[String, @proton_client.ClientFailure]] = Ref(
            Err(
              TransportFailure(
                message="the connection to Mission Control ended before the reply",
              ),
            ),
          )
          // The end of the connection cancels this task, and the caller still gets
          // the failure.
          defer (match reply.val {
            Ok(text) => success(text)
            Err(error) => failure(error)
          })
          reply.val = Ok((line.call)(method_name(route), request)) catch {
            error => Err(call_failure(error))
          }
        })
        run_tasks()
        () => task.cancel()
      },
      subscribe=(route, receive) => {
        let name = method_name(route)
        let listener = { receive, }
        match listeners.get(name) {
          Some(others) => listeners[name] = [..others, listener]
          None => {
            listeners[name] = [listener]
            if current.val is Some({ line, .. }) {
              listen(line, name)
            }
          }
        }
        () => {
          listeners[name] = listeners
            .get(name)
            .unwrap_or([])
            .filter(other => !physical_equal(other, listener))
        }
      },
    ),
    run: on_state => {
      report.val = on_state
      on_state(progress.val.state)
      @async.with_task_group(group => {
        group.spawn_bg(no_wait=true, connect)
        while !progress.val.is_final() {
          end.wait()
        }
        group.return_immediately()
      })
    },
    stopped: () => {
      step(Ended)
      end.signal()
      run_tasks()
    },
  }
}

///|
/// The time that a try has to open a connection, in milliseconds. A program that
/// accepts the port and does not answer would hold the try for minutes.
let open_limit : Int32 = 10000

///|
/// A try did not open a connection in `open_limit`.
priv suberror NotOpenInTime

///|
impl Show for NotOpenInTime with fn output(_self, logger) {
  logger.write_string(
    "the server did not answer in \{open_limit / 1000} seconds",
  )
}

///|
/// Runs `open` with `body`, and stops it when it does not give an open connection in
/// `open_limit`. The time of `body` has no limit.
async fn open_in_time(
  open : async (async (Line) -> Unit) -> Unit,
  sleep : async (Int32) -> Unit,
  body : async (Line) -> Unit,
) -> Unit {
  let late = Ref(false)
  @async.with_task_group(group => {
    let limit = group.spawn(no_wait=true, () => {
      sleep(open_limit)
      late.val = true
      group.return_immediately()
    })
    open(line => {
      // The limit can come in the same turn as the connection, and it is the first.
      guard !late.val else { raise NotOpenInTime }
      limit.cancel()
      body(line)
    })
  }) catch {
    // A stopped `open` can also raise an error, which does not give the cause.
    _ if late.val => ()
    error => raise error
  }
  if late.val {
    raise NotOpenInTime
  }
}

///|
/// Starts the tasks that are ready. An event of the page, such as a click, is not a
/// task of the async runtime. A task that it makes ready waits for the next timer or
/// message of the runtime, if nothing starts it.
fn run_tasks() -> Unit {
  ignore(@js_async.Promise::from_async(() => ()))
}

///|
/// The hub method or event of a Proton route, such as `app:list_projects`.
fn method_name(
  route : String,
) -> @signalr.MethodName raise @proton_client.ClientFailure {
  @signalr.MethodName::parse(route) catch {
    error => raise InvalidContract(message=error.message())
  }
}

///|
/// The failure that the UI gets for an error of a call. The server refuses a call
/// with a `HubError`, whose text is for the user.
fn call_failure(error : Error) -> @proton_client.ClientFailure {
  match error {
    @signalr.HubError(text) =>
      RemoteFailure(code="refused", message=text, detail=None)
    @proton_client.ClientFailure::InvalidContract(message~) =>
      InvalidContract(message~)
    error => TransportFailure(message=error.to_string())
  }
}

///|
/// Gives the function that connects to the hub at `url` with the key, and runs its
/// argument with the open connection. The argument and the reply of each method, and
/// the payload of each event, are one JSON value. `log` gets the error text of the end
/// of a connection, and each event that does not have one value.
fn hub_at(
  url : String,
  key : ViewKey,
  log : (String) -> Unit,
) -> (async (async (Line) -> Unit) -> Unit) raise @client.HubUrlError {
  let hub = @client.HubUrl::parse(url)
  body => open_hub(hub, key, log, body)
}

///|
async fn open_hub(
  hub : @client.HubUrl,
  key : ViewKey,
  log : (String) -> Unit,
  body : async (Line) -> Unit,
) -> Unit {
  let closed = Ref(false)
  let close = @async.Cond()
  let options = @client.ClientOptions::new(
    access_token=() => Some(key.token),
    on_handler_error=(name, error) => {
      let cause = match error {
        // The only error of a decoder that takes each value.
        @signalr.LengthMismatch(..) as error => error.message()
        error => error.to_string()
      }
      log("Mission Control sent a wrong event \{name}: \{cause}")
    },
    on_close=info => {
      if info.error is Some(text) {
        log("The connection to Mission Control ended: \{text}")
      }
      closed.val = true
      close.broadcast()
    },
  )
  @client.connect(hub, options~, connection => {
    body({
      call: (name, request) => {
        let hub_method = @signalr.HubMethod::call(
          name,
          @signalr.args1(@signalr.hub_value()),
          @signalr.hub_value(),
        )
        connection
        .invoke(hub_method, @signalr.HubValue::parse_json(request))
        .to_json_text()
      },
      listen: (name, handler) => {
        let event = @signalr.ClientMethod::new(
          name,
          @signalr.args1(@signalr.hub_value()),
        )
        connection.on(event, payload => handler(payload.to_json_text()))
      },
      lost: () => {
        while !closed.val {
          close.wait()
        }
      },
    })
  })
}

///|
// This test is here, because only this file names SignalR.
test "the failure that the UI gets for an error of a call" {
  assert_eq(
    call_failure(@signalr.HubError("The folder /code/reserch does not exist.")),
    RemoteFailure(
      code="refused",
      message="The folder /code/reserch does not exist.",
      detail=None,
    ),
  )
  let other = try {
    ignore(@signalr.HubValue::parse_json("{"))
    None
  } catch {
    error => Some(call_failure(error))
  }
  assert_true(other is Some(TransportFailure(_)))
}