#######################################################
# This file was auto-generated by elixir_bindings.zig #
#              Do not manually modify.                #
#######################################################

defmodule TigerBeetlex.TransferFlags do
  @moduledoc """
  See [TransferFlags](https://docs.tigerbeetle.com/reference/transfer#flags).
  """

  use TypedStruct

  typedstruct do
    field :linked, boolean(), default: false
    field :pending, boolean(), default: false
    field :post_pending_transfer, boolean(), default: false
    field :void_pending_transfer, boolean(), default: false
    field :balancing_debit, boolean(), default: false
    field :balancing_credit, boolean(), default: false
    field :closing_debit, boolean(), default: false
    field :closing_credit, boolean(), default: false
    field :imported, boolean(), default: false
  end

  @doc """
  Creates a `TigerBeetlex.TransferFlags` struct from its binary representation.
  """
  @spec from_binary(binary :: <<_::16>>) :: t()
  def from_binary(<<n::unsigned-little-16>> = _bin) do
    <<
      _padding::7,
      imported::1,
      closing_credit::1,
      closing_debit::1,
      balancing_credit::1,
      balancing_debit::1,
      void_pending_transfer::1,
      post_pending_transfer::1,
      pending::1,
      linked::1
    >> = <<n::unsigned-big-16>>

    %__MODULE__{
      linked: linked == 1,
      pending: pending == 1,
      post_pending_transfer: post_pending_transfer == 1,
      void_pending_transfer: void_pending_transfer == 1,
      balancing_debit: balancing_debit == 1,
      balancing_credit: balancing_credit == 1,
      closing_debit: closing_debit == 1,
      closing_credit: closing_credit == 1,
      imported: imported == 1
    }
  end

  @doc """
  Converts a `TigerBeetlex.TransferFlags` struct to its binary represenation.
  """
  @spec to_binary(flags :: t()) :: <<_::16>>
  def to_binary(flags) do
    %__MODULE__{
      linked: linked,
      pending: pending,
      post_pending_transfer: post_pending_transfer,
      void_pending_transfer: void_pending_transfer,
      balancing_debit: balancing_debit,
      balancing_credit: balancing_credit,
      closing_debit: closing_debit,
      closing_credit: closing_credit,
      imported: imported
    } = flags

    <<n::unsigned-big-16>> =
      <<
        # padding
        0::7,
        bool_to_u1(imported)::1,
        bool_to_u1(closing_credit)::1,
        bool_to_u1(closing_debit)::1,
        bool_to_u1(balancing_credit)::1,
        bool_to_u1(balancing_debit)::1,
        bool_to_u1(void_pending_transfer)::1,
        bool_to_u1(post_pending_transfer)::1,
        bool_to_u1(pending)::1,
        bool_to_u1(linked)::1
      >>

    <<n::unsigned-little-16>>
  end

  @spec bool_to_u1(b :: boolean()) :: 0 | 1
  defp bool_to_u1(true), do: 1
  defp bool_to_u1(false), do: 0
end
