# 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 Boolean
    #
    # BOOLEAN is a primitive type to handle true or false values.
    # @example Booelan
    #   bool = RASN1::Types::Boolean.new(value: true)
    #   bool2 = RASN1.parse(bool.to_der)
    #   bool2.class       #=> RASN1::Types::Boolean
    #   bool3.value       #=> true
    #
    # @author Sylvain Daubert
    # @author LemonTree55
    class Boolean < Primitive
      # Boolean id value
      ID = 0x01

      # DER true value
      DER_TRUE = 0xff
      # DER false value
      DER_FALSE = 0

      # @return [false]
      def void_value # rubocop:disable Naming/PredicateMethod
        false
      end

      # Make boolean value from DER/BER string.
      # @param der [String]
      # @param ber [::Boolean]
      # @return [void]
      # @see Types::Base#der_to_value
      # @raise [ASN1Error] +der+ is not 1-byte long
      # @raise [ASN1Error] +der+ is not {DER_TRUE} nor {DER_FALSE} and +ber+ is +false+
      def der_to_value(der, ber: false)
        raise ASN1Error, "tag #{@name}: BOOLEAN should have a length of 1" unless der.size == 1

        bool = der.unpack1('C')
        case bool
        when DER_FALSE
          @value = false
        when DER_TRUE
          @value = true
        else
          raise ASN1Error, "tag #{@name}: bad value 0x%02x for BOOLEAN" % bool unless ber

          @value = true
        end
      end

      private

      # @return [String]
      def value_to_der
        [@value ? DER_TRUE : DER_FALSE].pack('C')
      end

      # @return [String]
      def trace_data
        return super if explicit?

        "    #{raw_data == "\x00".b ? 'FALSE' : 'TRUE'} (0x#{bin2hex(raw_data)})"
      end
    end
  end
end
