def toggle_on_name_seq(seq)
  seq.name.split("_").last.to_i.odd?
end

def ip_from_seq(seq)
  ip = 0xFFFFFFFF - seq
  "#{ip >> 24}.#{ip >> 16 & 0xFF}.#{ip >> 8 & 0xFF}.#{ip & 0xFF}"
end

def mac_from_seq(seq)
  ip = (0xFFFFFFFFFFFF - seq).to_s(16)
  [10, 8, 6, 4, 2].each { |i| ip.insert(i, ':') }
  ip
end

def seq_padded_for_sorting(n)
  n.to_s.rjust(13, '0') # pad to 13 for max region size
end

require 'factory_bot'

# In case we are running as an engine, the factories are located in the Rails application
FactoryBot.definition_file_paths << Rails.root.join('spec/factories')

# Also, add factories from provider gems until miq codebase does not use any provider specific factories anymore
Rails::Engine.subclasses.select { |e| e.name.starts_with?("ManageIQ::Providers") }.each do |engine|
  FactoryBot.definition_file_paths << engine.root.join('spec', 'factories')
end

# Prefer setting the definition_file_paths and call FactoryBot.reload, which will recreate the configuration
# and call find_definitions.
#
# find_definitions is not reentrant, so a second call will lead to loading already registered factories.
# Other code, such as factory bot rails, may have already registered factories, so we can't assume
# we're the first to call find_definitions.
FactoryBot.definition_file_paths = FactoryBot.definition_file_paths.uniq

FactoryBot.reload

FactoryBot.define do
  trait :other_region do
    transient do
      other_region { nil }
    end

    after(:build) do |instance, evaluator|
      unless MiqRegion.my_region
        raise "You need to seed default MiqRegion with MiqRegion.seed"
      end

      unless evaluator.other_region
        raise "You need to pass specific region  with :other_region: \n" \
              "FactoryBot.create(:#{instance.class.to_s.tableize.singularize.to_sym}, :in_other_region, :other_region => <region>) "
      end

      sequence_id = "id_for_other_region_#{instance.class}_#{evaluator.other_region}".to_sym
      @sequence ||= {}
      @sequence[sequence_id] ||= FactoryBot::Syntax::Default::DSL.new.sequence(sequence_id) { |n| instance.class.id_in_region(n, evaluator.other_region.region) }
      instance.id = generate(sequence_id)
    end
  end
end
