require 'rails_admin/config/fields'
require 'rails_admin/config/fields/types'
require 'rails_admin/config/fields/types/file_upload'

# Register a custom field factory
RailsAdmin::Config::Fields.register_factory do |parent, properties, fields|
  dragonfly_columns = [:uid]
  model = parent.abstract_model.model
  if defined?(::Dragonfly) and model.kind_of?(Dragonfly::ActiveModelExtensions::ClassMethods)
    if part = dragonfly_columns.detect {|it| properties[:name].to_s.strip =~ /^(.+)_#{it}$/ }
      attachment_name = properties[:name].to_s.scan(/^(.+)_#{part}$/).first.first.to_sym
      if fields.find{|f| attachment_name == f.name}.nil?
        dragonfly_columns.each do |it|
          if props = parent.abstract_model.properties.find {|p| "#{attachment_name}_#{it}" == p[:name].to_s }
            RailsAdmin::Config::Fields.default_factory.call(parent, props, fields)
            fields.last.hide
          end
        end
        fields << RailsAdmin::Config::Fields::Types::DragonflyFile.new(parent, attachment_name, properties)
        true
      end
    end
  else
    false
  end
end
