app/models/coupdoeil/hovercard/option/offset.rb



# frozen_string_literal: true

module Coupdoeil
  class Hovercard
    class Option
      class Offset < Coupdoeil::Hovercard::Option
        self.bit_size = 8 + 11 + 2

        class << self
          def parse(value)
            float_value = value.to_f
            return 0 if float_value.zero?

            base = 0
            base |= 1 if float_value.negative?
            base |= 2 if value.is_a?(String) && value.end_with?("rem")

            integer, decimals = float_value.abs.to_s.split(".")
            base |= (decimals.to_i << 2)
            base |= (integer.to_i << 2 + 11)

            base
          end
        end

        def validate!
          return if value in Float | Integer
          return if value.to_s.match?(/^-?\d+(\.\d{1,3})?(px|rem)?$/)

          raise_invalid_option "Value should be a signed float or integer, followed or not by 'rem' or 'px'."
        end
      end
    end
  end
end