# frozen_string_literal: true

# This file is part of RASN1
# See https://codeberg.org/lemontree55/rasn1 for more informations
# Copyright (C) 2016-2024 Sylvain Daubert <sylvain.daubert@laposte.net>
# Copyright (C) 2024 LemonTree55 <lenontree@proton.me>
# This program is published under MIT license.

module RASN1
  module Types
    # ASN.1 Enumerated
    #
    # An ENUMERATED type permits to assign names to integer values. {Integer} may
    # also be enumerated, but the tag {ID} is different.
    #
    # @example Example 1
    #  enum = RASN1::Types::Enumerated.new(enum: { 'a' => 0, 'b' => 1, 'c' => 2 })
    #  enum.value = 'a'
    #  enum.value       # => 'a'
    # @example Example 2
    #  enum = RASN1::Types::Enumerated.new(enum: { a: 0, b: 1, c: 2 })
    #  enum.value = :b
    #  enum.value = 1   # equivalent to :b
    #  # enum returned value is always symbolic (even if set with an integer)
    #  enum.value       # => :b
    # A {EnumeratedError} is raised when set value is not in enumeration.
    # @author Sylvain Daubert
    class Enumerated < Integer
      # @!attribute enum
      # @return [Hash]

      # Enumerated id value
      ID = 0x0a

      # @option options [Hash] :enum enumeration hash. Keys are names, and values
      #   are integers. This key is mandatory.
      # @raise [EnumeratedError] +:enum+ key is not present
      # @raise [EnumeratedError] +:default+ value is unknown
      # @see Base#initialize common options to all ASN.1 types
      def initialize(options={})
        super
        raise EnumeratedError, 'no enumeration given' if @enum.empty?
      end

      # @return [Hash]
      def to_h
        @enum
      end
    end
  end
end
