# NOTE: When changing this file make sure to also change # reindex_elasticsearch.rake within profile publisher as well.

namespace :elasticsearch do

desc 'Reindex all the models.'
task reindex: [:environment] do
  [
    PageEdition, SiteCategory, Person, Group, ServiceLink, Article,
    Department, AcademicProgram, Event, AcademicCard
  ].each do |klass|
    puts "Reimporting #{klass.to_s.pluralize} into elasticsearch..."
    # This will loop through and index each object, applying the correct
    # rules to each one.
    klass.each do |k|
      k.add_to_index if k.present?
    end
  end
  puts "\nAll done!\n\n"
end

# Index Model Helpers
def index_collection(collection)
  collection.each do |coll|
    coll.add_to_index if coll.present?
  end
end

def index_models(models)
  models.each do |klass|
    puts "Importing #{klass.to_s.pluralize}..."
    index_collection(klass)
  end
end

# Delete all indexes and the recreate them
def delete_and_create_index
  config = BuwebContentModels.config
  client = Elasticsearch::Model.client
  index = Settings.elasticsearch.index_name
  begin
    client.indices.delete index: index
  rescue Elasticsearch::Transport::Transport::Errors::NotFound
    puts 'Index doesn\'t exist... '
  end
  client.indices.create index: index, body: {
    settings: config.elasticsearch_settings,
    mappings: config.elasticsearch_mappings
  }
end

desc 'Delete and Create Elasticsearch Index'
task hard_reindex: [:environment] do
  delete_and_create_index
  index_models [Department, Group]
  puts 'Importing employees...'
  index_collection Person.where(
    '$or' => [
      { affiliations: 'faculty' },
      { affiliations: 'employee' }
    ]
  )

  puts 'Importing students...'
  index_collection Person.where(affiliations: 'student')

  index_models [
    AcademicProgram, ServiceLink, Article, Event, SiteCategory, PageEdition, AcademicCard
  ]

  puts 'Importing everyone else...'
  index_collection Person

  puts "\nAll done!\n\n"
end

end