module Rspec::Dunlop::GeneralHelpers
  def fixture_file(filename)
    File.open fixture_path.join(filename)
  end

  def read_zipfile(filename)
    case %x[file #{filename}]
    when /gzip/i
      output = ""
      Zlib::GzipReader.open(filename) do |gz|
        output << gz.read
      end
      output
    when /zip/i
      output = ""
      Zip::InputStream::open(filename) do |io|
        while (entry = io.get_next_entry)
          output << io.read
        end
      end
      output
    else
      File.read(filename)
    end
  end

  # Wait for the database to have finished the update stuff, then reload
  # the models. Threading might give inconsistent data
  def reload_model(*models)
    if respond_to?(:page) and page.respond_to?(:driver)
      case page.driver.class.name.underscore
      when /poltergeist/
        # I don't know, but there seems to be a chronoligical misbehavior overhere
        sleep 0.3
      end
    end
    models.each &:reload
  end
  alias_method :reload_models, :reload_model

  def click_on_translation(path, options = {})
    translated_value = I18n.t(path, options.merge(default: 'TRANSLATION-NOT-FOUND'))
    raise "Translation #{path} not found" if translated_value.blank? or translated_value == 'TRANSLATION-NOT-FOUND'
    click_on translated_value
  end

  def click_on_selector(selector)
    find(selector).click
  end

end
