///|
/// Native controlling-terminal backend backed by `moonbitlang/core/async/tty`.
#warnings("-14")
type Backend = @core_tty.Tty

///|
#warnings("-14")
async fn open_backend() -> Backend {
  @core_tty.open()
}

///|
fn backend_size(backend : Backend) -> (Int32, Int32) raise @os_error.OSError {
  backend.size() catch {
    @core_os_error.OsError(_, raw_code~, context~) =>
      raise OSError(raw_code, context~)
    err => raise OSError(@os_error.errno_ENOTSUP, context=err.to_string())
  }
}

///|
#warnings("-unused_async")
async fn backend_enter_raw_mode(backend : Backend) -> Unit {
  backend.enter_raw_mode()
}

///|
#warnings("-unused_async")
async fn backend_leave_raw_mode(backend : Backend) -> Unit nocancel {
  backend.leave_raw_mode()
}

///|
#warnings("-unused_async")
async fn backend_close(backend : Backend) -> Unit nocancel {
  backend.leave_raw_mode() catch {
    _ => ()
  }
}

///|
async fn backend_write(backend : Backend, bytes : BytesView) -> Unit {
  backend.write(bytes)
}

///|
impl @input.ByteReader for Tty with fn read_byte(self) {
  match self.backend.wait_resize() {
    Resize => raise Resized
    Input => self.backend.read_exactly(1)[0]
  }
}