#' Metadata about a remote table
#'
#' `remote_name()` gives the unescaped name of the remote table, or `NULL` if it
#' is a query (created by `sql()`) or already escape (created by `ident_q()`).
#' `remote_table()` gives the remote table or the query.
#' `remote_query()` gives the text of the query, and `remote_query_plan()`
#' the query plan (as computed by the remote database). `remote_src()` and
#' `remote_con()` give the dplyr source and DBI connection respectively.
#'
#' @param x Remote table, currently must be a [tbl_sql].
#' @param null_if_local Return `NULL` if the remote table is created via
#'   `tbl_lazy()` or `lazy_frame()`?
#' @param cte `r lifecycle::badge("deprecated")`
#'   Use the `render_otions` argument instead.
#' @param sql_options `r lifecycle::badge("experimental")`
#'   SQL rendering options generated by `sql_options()`.
#' @param ... Additional arguments passed on to methods.
#' @return The value, or `NULL` if not remote table, or not applicable.
#'    For example, computed queries do not have a "name"
#' @export
#' @examples
#' mf <- memdb_frame(x = 1:5, y = 5:1, .name = "blorp")
#' remote_name(mf)
#' remote_src(mf)
#' remote_con(mf)
#' remote_query(mf)
#'
#' mf2 <- dplyr::filter(mf, x > 3)
#' remote_name(mf2)
#' remote_src(mf2)
#' remote_con(mf2)
#' remote_query(mf2)
remote_name <- function(x, null_if_local = TRUE) {
  table <- remote_table(x, null_if_local = null_if_local)

  if (is.sql(table) || is.null(table)) {
    NULL
  } else {
    con <- remote_con(x)
    if (is.null(con)) {
      table
    } else {
      table_path_name(table, con)
    }
  }
}

#' @export
#' @rdname remote_name
remote_table <- function(x, null_if_local = TRUE) {
  check_bool(null_if_local)

  UseMethod("remote_table")
}

#' @export
remote_table.tbl_lazy <- function(x, null_if_local = TRUE) {
  remote_table(x$lazy_query, null_if_local = null_if_local)
}

#' @export
remote_table.lazy_base_remote_query <- function(x, null_if_local = TRUE) {
  x$x
}

#' @export
remote_table.lazy_base_local_query <- function(x, null_if_local = TRUE) {
  if (null_if_local) {
    return()
  }

  x$name
}

#' @export
remote_table.lazy_query <- function(x, null_if_local = TRUE) {
  if (!is_lazy_select_query_simple(x, ignore_group_by = TRUE, select = "identity")) {
    return()
  }

  remote_table(x$x)
}

#' @export
#' @rdname remote_name
remote_src <- function(x) {
  x$src
}

#' @export
#' @rdname remote_name
remote_con <- function(x) {
  x$src$con
}

#' @export
#' @rdname remote_name
remote_query <- function(x, cte = FALSE, sql_options = NULL) {
  db_sql_render(remote_con(x), x, cte = cte, sql_options = sql_options)
}

#' @export
#' @rdname remote_name
remote_query_plan <- function(x, ...) {
  dbplyr_explain(remote_con(x), db_sql_render(remote_con(x), x$lazy_query), ...)
}
