package gs.std.v0.core

import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.util.Base64

/** Implementation of [[Encoder]] for Base64.
  *
  * Supports base64-url encoding as well.
  */
object Base64Encoder extends Encoder[B64]:

  private lazy val e: Base64.Encoder  = Base64.getEncoder()
  private lazy val eu: Base64.Encoder = Base64.getUrlEncoder()

  /** @inheritDocs
    */
  override def encode(input: Array[Byte]): B64 =
    B64(e.encodeToString(input))

  /** @inheritDocs
    */
  override def encode(input: Vector[Byte]): B64 =
    B64(e.encodeToString(input.toArray))

  /** Encode the given bytes using base64-url.
    *
    * @param input
    *   The input data.
    * @return
    *   The base64-url-encoded string.
    */
  def encodeUrl(input: Array[Byte]): B64Url =
    B64Url(eu.encodeToString(input))

  /** Encode the given bytes using base64-url.
    *
    * @param input
    *   The input data.
    * @param charset
    *   The character set of the input data.
    * @return
    *   The base64-url-encoded string.
    */
  def encodeUrl(
    input: String,
    charset: Charset = StandardCharsets.UTF_8
  ): B64Url =
    encodeUrl(input.getBytes(charset))
