
# Asset groups
if (Rails.groups.map(&:to_s) & %w[development assets test]).any?
  require "font-awesome-rails"
  require "sass-rails"
  require "js-routes"
  require "momentjs-rails"
  require 'coffee-rails'
  require "pickadate-rails"
end

require "slim-rails"
require 'record_collection'
require 'request_store'
require 'ransack'
require 'devise'
require 'devise-token_authenticatable'
require 'state_machines-activerecord'
require 'carrierwave'
require 'simple_form'
require 'redcarpet'
require 'exception_notification'
require 'facets/enumerable/map_send'
require 'memoist'
require 'cancancan'

if Rails::VERSION::MAJOR < 5
  ActiveRecord::Associations::Builder::Association.valid_options |= [:optional]
  class ActiveRecord::Migration
    # rails5 compatibility
    def self.[](*)
      self
    end
  end
end

module Dunlop
  class Engine < ::Rails::Engine
    isolate_namespace Dunlop

    #TODO this generates noise and pollutes API based implementations (Like Panda)
    initializer 'dunlop.action_controller' do |app|
      ActiveSupport.on_load :action_controller do
        helper Dunlop::ApplicationHelper if respond_to?(:helper)
      end
    end

    initializer "dunlop.ability", group: 'dunlop' do |app|
      if ability_class = "Ability".safe_constantize and ability_class.respond_to?(:add_dunlop_allowed_authorization_classes!)
        ability_class.add_dunlop_allowed_authorization_classes!
      end
    end

    # add migrations to containing application
    initializer 'dunlop.append_migrations' do |app|
      unless app.root.to_s.match root.to_s
        config.paths["db/migrate"].expanded.each do |expanded_path|
          app.config.paths["db/migrate"] << expanded_path
        end
      end
    end

    config.after_initialize do
      # Auto generate target-file's ::Job classes having purpose triggering .generate on the class
      Dunlop.target_file_models.each do |target_file_base_model|
        ## Generte a job for all target files
        base_job =  "#{target_file_base_model.name.deconstantize}::ApplicationJob".constantize
        target_file_base_model.classes.each do |cls|
          next if cls.const_defined?(:Job)
          cls::Job = Class.new base_job do
            def perform
              self.class.name.sub(/::Job$/, '').constantize.generate!
            end
          end
        end
      end
    end
  end
end
