# == Schema Information
#
# Table name: indexers
#
#  id           :integer          not null, primary key
#  klass        :string
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#  params       :text(4294967295)
#  name         :string
#  enabled      :boolean          default(TRUE)
#  last_updated :datetime
#

class Indexer < ActiveRecord::Base
  has_many :releases
  validates :name, presence: true
  validates :klass, presence: true
  validates :params, presence: true
  validate :test_indexer
  after_initialize :init_params

  serialize :params

  scope :enabled, -> { where(enabled: true) }

  def test_indexer
    return unless changed.include? :params
    indexer_client = initialize_indexer
    indexer_client.test
  rescue Faraday::ConnectionFailed
    errors[:base] << 'We couldn\'t talk to the indexer using these settings'
  end

  def initialize_indexer
    client = Indexers::AvailableClients.constant_for(klass)
    init_params = [self].concat client.init_params.map { |param| params.fetch param, '' }
    client.new(*init_params)
  end

  private

  def init_params
    self.params ||= {}
  end
end
