Rack::Utils.multipart_part_limit = 0

require_relative './lib/easy_extensions/easy_extensions'
require_relative './lib/easy_extensions/easy_quotes/easy_quotes_engine'
require_relative './lib/easy_extensions/after_start_scripts'
require_relative './lib/easy_extensions/easy_proposer'
require 'net/imap'

ActiveSupport::Dependencies.autoload_paths << File.join(EasyExtensions::EASY_EXTENSIONS_DIR, 'app','controllers', 'admin')

ActionView::Base.send(:include, EntityAttributeHelper)

relative_paths = ['/lib/utils', '/lib/easy_patch/core', '/lib/easy_patch/rails', '/lib/easy_patch/paperclip', '/lib/easy_patch/plugins',
  '/lib/easy_patch/redmine/others', '/lib/easy_patch/redmine/controllers', '/lib/easy_patch/redmine/helpers', '/lib/easy_patch/redmine/models']
relative_paths.each do |path|
  Dir.entries(File.dirname(__FILE__) + path).each do |file|
    next unless file.end_with?('.rb')
    require_relative "./#{path}/#{file}"
  end
end

Dir[File.dirname(__FILE__) + '/test/mailers/previews/*.rb'].each {|file| require_dependency file } if Rails.env.development?

require 'openssl'
silence_warnings do
  OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
end

if EasyExtensions::EasyProjectSettings.enable_copying_files_on_restart
  begin
    FileUtils.cp("#{EasyExtensions::PATH_TO_EASYPROJECT_ROOT}/easy_plugins/easy_extensions/lib/easy_patch/to_copy/404.html", "#{Rails.root}/public/404.html")
    FileUtils.cp("#{EasyExtensions::PATH_TO_EASYPROJECT_ROOT}/easy_plugins/easy_extensions/lib/easy_patch/to_copy/500.html", "#{Rails.root}/public/500.html")
    FileUtils.cp("#{EasyExtensions::PATH_TO_EASYPROJECT_ROOT}/easy_plugins/easy_extensions/lib/easy_patch/to_copy/browserconfig.xml", "#{Rails.root}/public/browserconfig.xml")
    # FileUtils.cp("#{EasyExtensions::PATH_TO_EASYPROJECT_ROOT}/easy_plugins/easy_extensions/assets/images/favicon.ico", "#{Rails.root}/public/favicon.ico")
    # FileUtils.cp("#{EasyExtensions::PATH_TO_EASYPROJECT_ROOT}/easy_plugins/easy_extensions/lib/easy_patch/to_copy/application.js", "#{Rails.root}/public/javascripts/application.js")
    FileUtils.cp("#{EasyExtensions::PATH_TO_EASYPROJECT_ROOT}/easy_plugins/easy_extensions/lib/easy_patch/to_copy/20150921204850_change_time_entries_comments_limit_to_1024.rb", "#{Rails.root}/db/migrate/20150921204850_change_time_entries_comments_limit_to_1024.rb")
  rescue
  end
end

# Load plurals langfiles.
I18n.load_path += Dir[File.join(EasyExtensions::EASY_EXTENSIONS_DIR, 'config', 'locales', '*.{rb}')]
I18n.enforce_available_locales = false

# ActionController::Session::CookieStore::CookieOverflow Error
ActionDispatch::Cookies.send(:remove_const, :MAX_COOKIE_SIZE)
ActionDispatch::Cookies.const_set(:MAX_COOKIE_SIZE, 8.kilobytes)

Rails.application.configure do
  config.redmine_verify_sessions = false
  config.active_record.observers = [:issue_invitation_observer]

  assets_dir = Redmine::Plugin.find(:easy_extensions).assets_directory
  config.assets.paths << File.join(assets_dir, 'easy_fonts')
  config.assets.paths << File.join(assets_dir)
  config.assets.precompile.concat Dir.glob(File.join(assets_dir, 'easy_fonts', '*'))
  precompile_css = %w(easy_print.css easy_theme.css easy_chart/c3.css easy_jquery_ui/jquery-ui.css)
  precompile_js = %w(easy_page.js easygantt.js galereya/jquery.galereya.js easy_project_form.js easy_chart/easy_chart.js grid/grid.js)
  precompile_js.concat %w(jquery.color.js avatarcrop.js)
  config.assets.precompile.concat precompile_css.collect{|n| File.join(assets_dir, 'stylesheets', n) }
  config.assets.precompile.concat precompile_js.collect{|n| File.join(assets_dir, 'javascripts', n) }

  config.assets.precompile += %w( cocoon.js )
  config.assets.precompile << File.join(assets_dir, 'javascripts', 'dart.js')
  config.assets.precompile << File.join(assets_dir, 'javascripts', 'dart.min.js')
end

Geocoder.configure( {cache: Rails.cache} )

EasyExtensions::PatchManager.register_easy_page_controller 'EasyPageLayoutController', 'EasyPageTemplateLayoutController', 'EasyResourceAvailabilitiesController',
  'MyController', 'ProjectsController', 'UsersController', 'EasyPageTemplatesController', 'EasyQueriesController', 'EasyPagesController', 'EasyExtensions::Export::Pdf',
  'EasyEntityAssignmentsController', 'EasyPageTabsController'

EasyExtensions::PatchManager.register_easy_page_helper 'AttachmentsHelper', 'CustomFieldsHelper', 'EasyAttendancesHelper',
  'EasyIconsHelper', 'EasyJournalHelper', 'EasyPageModulesHelper', 'EasyQueryHelper',
  'IssuesHelper', 'IssueRelationsHelper', 'JournalsHelper', 'ProjectsHelper', 'SortHelper', 'TimelogHelper', 'UsersHelper', 'EasyRakeTasksHelper', 'EasyActivitiesHelper'

require_relative './lib/easy_extensions/easy_translator'
require_dependency 'easy_extensions/easy_page_modules'

EpmRedmineModule.ensure_all

EasyExtensions::AfterInstallScripts.add do
  if Redmine::Plugin.installed?(:easy_printable_templates)
    EasyPrintableTemplate.create_from_view!(HashWithIndifferentAccess.new(:name => 'QR', :category => 'easy_qr'), :plugin_name => 'easy_extensions', :internal_name => 'easy_qr')
  end
end

EasyExtensions::AfterInstallScripts.add do
  EasyRakeTaskInfo.where(:status => EasyRakeTaskInfo::STATUS_RUNNING).update_all(:status => EasyRakeTaskInfo::STATUS_ENDED_FORCED)
end

# this block is runed once just after easyproject is started
# means after all plugins(easy) are initialized
ActiveSupport.on_load(:easyproject, yield: true) do
  require 'rails/observers/activerecord/active_record'

  require_relative './lib/easy_extensions/hooks'
  require_relative './lib/easy_extensions/menus'
  require_relative './lib/easy_extensions/permissions'
  require_relative './lib/easy_extensions/proposer'
  require_relative './lib/easy_extensions/internals'
  require_relative './lib/easy_extensions/easy_settings'

  # To prevent circular dependency error
  require_dependency 'easy_issue_mail_handler'
end

# this block is called every time rails are reloading code
# in development it means after each change in observed file
# in production it means once just after server has started
ActionDispatch::Reloader.to_prepare do

  if observers = Rails.configuration.active_record.observers
    ActiveRecord::Base.send :observers=, observers
  end

  Dir[File.dirname(__FILE__) + '/lib/easy_extensions/validators/*.rb'].each {|file| require_dependency file }
  Dir[File.dirname(__FILE__) + '/lib/easy_extensions/field_formats/*.rb'].each {|file| require_dependency file }
  Dir[File.dirname(__FILE__) + '/lib/easy_extensions/paperclip_preprocessors/*.rb'].each {|file| require_dependency file }
  Dir[File.dirname(__FILE__) + '/lib/easy_extensions/image_processing/*.rb'].each {|file| require_dependency file }
  Dir[File.dirname(__FILE__) + '/lib/easy_extensions/image_processing/adapters/*.rb'].each {|file| require_dependency file }
  Dir[File.dirname(__FILE__) + '/lib/easy_extensions/image_processing/adapters/*.rb'].each {|file| require_dependency file }
  Dir[File.dirname(__FILE__) + '/lib/easy_extensions/views/*.rb'].each {|file| require_dependency file }

  require_dependency 'easy_extensions/easy_xml_data/importer'
  require_dependency 'easy_version_category'
  require_dependency 'easy_extensions/yaml_encoder'
  require_dependency 'easy_extensions/easy_external_authentications/easy_external_authentication_provider'
  require_dependency 'easy_extensions/easy_entity_cards/base'
  require_dependency 'easy_extensions/easy_assets'
  require_dependency 'easy_extensions/easy_qr'
  require_dependency 'easy_extensions/easy_tag'
  require_dependency 'easy_extensions/easy_msg_reader'

  if Object.const_defined?(:Oj)
    Oj.optimize_rails
    Oj.default_options = {:mode => :rails}
  end

  # Touch to register subclass
  EasyProjectPriority
  EasyCustomFieldGroup

  # Jobs
  require 'easy_job'

  CustomFieldsHelper::CUSTOM_FIELDS_TABS << {:name => EasyProjectTemplateCustomField.name, :partial => 'custom_fields/index', :label => :label_templates_plural}
  CustomFieldsHelper::CUSTOM_FIELDS_TABS << {:name => 'AttachmentCustomField', :partial => 'custom_fields/index', :label => :label_attachment_plural}

  Redmine::Search.map do |search|
    search.unregister :projects
    EasyExtensions::EasyProjectSettings.disabled_features[:search_types].each{|s_t| search.unregister s_t}
  end

  Redmine::Search.map do |search|
    search.register :project
  end

  #EasyExtensions.debug_mode = true
  if EasyExtensions.debug_mode
    puts 'WARNING: starting in a debug mode!'
    require 'easy_extensions/easy_performance_watcher'
    Dir[File.dirname(__FILE__) + '/lib/easy_patch/debug/*.rb'].each {|file| require file }
  end


  require_relative './lib/easy_extensions/easy_repeaters'
  EasyExtensions::EntityRepeater.map do |mapper|
    mapper.register EasyExtensions::IssueRepeater.new
  end

  #Mime::Type.register 'text/calendar', :ics
  #Mime::Type.register_alias 'text/html', :mobile
  Redmine::MimeType.register_mime_type 'application/eml', 'eml'
  #for evernote audio files
  Redmine::MimeType.register_mime_type 'audio/wav', 'wav'
  Redmine::MimeType.register_mime_type 'audio/mpeg', 'mp3'
  Redmine::MimeType.register_mime_type 'audio/amr', 'amr'

  # excel export
  Mime::Type.register 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', :xlsx
  Mime::Type.register_alias 'text/javascript', :qr

  Dir.entries(File.dirname(__FILE__) + '/lib/easy_extensions/easy_lookups').each do |file|
    next unless file.end_with?('.rb')
    require_relative "./lib/easy_extensions/easy_lookups/#{file}"
  end
  EasyExtensions::EasyLookups::EasyLookup.map do |easy_lookup|
    easy_lookup.register EasyExtensions::EasyLookups::EasyLookupDocument.new
    easy_lookup.register EasyExtensions::EasyLookups::EasyLookupGroup.new
    easy_lookup.register EasyExtensions::EasyLookups::EasyLookupIssue.new
    easy_lookup.register EasyExtensions::EasyLookups::EasyLookupProject.new
    easy_lookup.register EasyExtensions::EasyLookups::EasyLookupUser.new
    easy_lookup.register EasyExtensions::EasyLookups::EasyLookupVersion.new
  end

  # EasyExtensions::Websocket::EventPublisher.start_polling!

  # List of queries displayed to user on review pages(etc. my_page, sidebar, ...)
  EasyQuery.map do |query|
    query.register EasyIssueQuery
    query.register EasyProjectQuery
    query.register EasyProjectTemplateQuery
    query.register EasyUserQuery
    query.register EasyVersionQuery
    query.register EasyAttendanceQuery
    query.register EasyTimeEntryQuery
    query.register EasyIssueTimerQuery
    query.register EasyEasyQueryQuery
    query.register EasyDocumentQuery
  end

  RedmineExtensions::BasePresenter.register 'EasyExtensions::EasyQueryHelpers::EasyQueryPresenter', 'EasyQuery'

  EasyExtensions::EasyQueryHelpers::EasyQueryOutput.register_output EasyExtensions::EasyQueryOutputs::ListOutput
  EasyExtensions::EasyQueryHelpers::EasyQueryOutput.register_output EasyExtensions::EasyQueryOutputs::ChartOutput
  EasyExtensions::EasyQueryHelpers::EasyQueryOutput.register_output EasyExtensions::EasyQueryOutputs::CalendarOutput
  EasyExtensions::EasyQueryHelpers::EasyQueryOutput.register_output EasyExtensions::EasyQueryOutputs::ReportOutput
  EasyExtensions::EasyQueryHelpers::EasyQueryOutput.register_output EasyExtensions::EasyQueryOutputs::TilesOutput
  EasyExtensions::EasyQueryHelpers::EasyQueryOutput.register_output EasyExtensions::EasyQueryOutputs::MapOutput

  %w(data file smb).each{|i| Loofah::HTML5::WhiteList::ALLOWED_PROTOCOLS.add(i)}

  ActiveSupport::Inflector.inflections do |inflect|
    inflect.uncountable 'GroupAnonymous'
  end

  EasySetting.map.boolean_keys(:project_calculate_start_date, :project_calculate_due_date, :timelog_comment_editor_enabled,
      :time_entry_spent_on_at_issue_update_enabled, :commit_logtime_enabled, :project_fixed_activity,
      :enable_activity_roles, :show_issue_id, :commit_cross_project_ref, :issue_recalculate_attributes,
      :use_easy_cache, :avatar_enabled, :show_personal_statement, :show_bulk_time_entry,
      :enable_private_issues, :display_issue_relations_on_new_form, :milestone_effective_date_from_issue_due_date,
      :allow_log_time_to_closed_issue, :project_display_identifiers, :issue_set_done_after_close, :allow_repeating_issues,
      :just_one_issue_mail, :required_issue_id_at_time_entry, :required_time_entry_comments, :close_subtask_after_parent, :show_time_entry_range_select,
      :easy_contact_toolbar_is_enabled, :issue_private_note_as_default, :show_easy_resource_booking,
      :skip_workflow_for_admin, :hide_login_quotes, :display_project_field_on_issue_detail,
      :easy_invoicing_use_estimated_time_for_issues, :easy_invoicing_use_easy_money_currency_settings, :hide_imagemagick_warning,
      :time_entries_locking_enabled, :display_journal_details,
      :easy_webdav_enabled,
      :show_avatars_on_query,
      :easy_user_allocation_by_project_enabled,
      :ckeditor_syntax_highlight_enabled,
      :issue_copy_notes_to_parent,
      :default_project_inherit_members,
      :ckeditor_autolink_file_protocols,
      :show_easy_custom_formatting,
      :show_easy_entity_activity_on_issue,
      :html5_dates,
      :dont_verify_server_cert
    )

  EasyExtensions::AfterStartScripts.execute

  EasyEntityActivityCategory
end

require 'easy_extensions/sso_easysoftware_com'
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :sso_easysoftware_com, '04fe1e0474667d64ef64265471796b0f', '9758d5479ca21d9f2e7b48548f8859c3'
end

# ActiveJob required (maybe later)
#
# require 'sucker_punch/async_syntax'
#
# Rails.application.configure do
#   config.active_job.queue_adapter = :sucker_punch
# end
