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

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

  use TypedStruct

  typedstruct do
    field :linked, boolean(), default: false
    field :debits_must_not_exceed_credits, boolean(), default: false
    field :credits_must_not_exceed_debits, boolean(), default: false
    field :history, boolean(), default: false
    field :imported, boolean(), default: false
    field :closed, boolean(), default: false
  end

  @doc """
  Creates a `TigerBeetlex.AccountFlags` struct from its binary representation.
  """
  @spec from_binary(binary :: <<_::16>>) :: t()
  def from_binary(<<n::unsigned-little-16>> = _bin) do
    <<
      _padding::10,
      closed::1,
      imported::1,
      history::1,
      credits_must_not_exceed_debits::1,
      debits_must_not_exceed_credits::1,
      linked::1
    >> = <<n::unsigned-big-16>>

    %__MODULE__{
      linked: linked == 1,
      debits_must_not_exceed_credits: debits_must_not_exceed_credits == 1,
      credits_must_not_exceed_debits: credits_must_not_exceed_debits == 1,
      history: history == 1,
      imported: imported == 1,
      closed: closed == 1
    }
  end

  @doc """
  Converts a `TigerBeetlex.AccountFlags` struct to its binary represenation.
  """
  @spec to_binary(flags :: t()) :: <<_::16>>
  def to_binary(flags) do
    %__MODULE__{
      linked: linked,
      debits_must_not_exceed_credits: debits_must_not_exceed_credits,
      credits_must_not_exceed_debits: credits_must_not_exceed_debits,
      history: history,
      imported: imported,
      closed: closed
    } = flags

    <<n::unsigned-big-16>> =
      <<
        # padding
        0::10,
        bool_to_u1(closed)::1,
        bool_to_u1(imported)::1,
        bool_to_u1(history)::1,
        bool_to_u1(credits_must_not_exceed_debits)::1,
        bool_to_u1(debits_must_not_exceed_credits)::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
