class InstitutionRemuneration < ActiveRecord::Base

  # Accessible attributes
  attr_accessible :individual_monthly_remuneration, :institution_id, :name, :other_remuneration,
    :total_employee, :line_of_work_id, :honorary, :wage_category, :public_official_name, :individual_overtime_remuneration

  # Associations
  belongs_to :institution
  belongs_to :line_of_work

  # Callbacks
  before_save :set_individual_monthly_remuneration

  # Validations
  validates :name, :institution_id, :wage_category, presence: true
  validates :total_employee, numericality: { only_integer: true, greater_than: 0 }
  validates :other_remuneration, numericality: true, allow_nil: true
  validates :individual_monthly_remuneration, numericality: { greater_than: 0.0 }, unless: Proc.new{ |obj| obj.honorary? }
  validates :individual_overtime_remuneration, numericality: true, allow_nil: true
  validates :institution_id, uniqueness: { scope: [:name, :total_employee, :individual_monthly_remuneration, :other_remuneration, :line_of_work_id, :honorary, :wage_category, :honorary], :message => "Datos del estandar ya se encuentran en uso"}

  

  # Will paginate uses this method
  # to know how many rows to show
  #
  def self.per_page
    50
  end

  def set_individual_monthly_remuneration
    self.individual_monthly_remuneration = 0 if self.honorary?
  end

  def data_for_csv
    [
      name,
      public_official_name,
      total_employee,
      individual_monthly_remuneration,
      other_remuneration,
      public_official_name,
      I18n.t(honorary?.to_s),
      wage_category
    ]
  end

  def self.header_for_csv
    [:name, :public_official_name, :total_employee, :individual_monthly_remuneration, :other_remuneration, :individual_overtime_remuneration, :honorary, :wage_category]
  end

  def self.attributes_for_grid
    [
      :line_of_work_id,
      :institution_id,
      :name,
      :public_official_name,
      :total_employee,
      :individual_monthly_remuneration,
      :other_remuneration,
      :individual_overtime_remuneration,
      :honorary,
      :wage_category
    ]
  end
  
  def self.dedupe
    # find all models and group them on keys which should be common
    grouped = all.group_by{|model| [model.institution_id, model.name, model.public_official_name, model.total_employee, model.individual_monthly_remuneration, model.other_remuneration, model.individual_overtime_remuneration, model.line_of_work_id, model.honorary, model.wage_category, model.honorary] }
    grouped.values.each do |duplicates|
      # the first one we want to keep right?
      first_one = duplicates.shift # or pop for last one
      duplicates.each{|double| double.destroy} # duplicates can now be destroyed
    end
  end
end
