class Procurement < ActiveRecord::Base
  attr_accessible :amount, :compliance_deadlines, :counterpart_name, :counterpart_info, 
                  :form_of_contract, :institution_id, :name, :start_date

  # Non database attributtes
  attr_accessible :attachment
  
  # Associations
  belongs_to :institution

  # Validations
  validates :institution_id, :name, :amount, presence: true
  validates :amount, numericality: true
  validates :institution_id, uniqueness: { scope: [:name, :amount, :counterpart_info, :compliance_deadlines, :form_of_contract, :counterpart_name, :start_date], :message => "Datos del estandar ya se encuentran en uso"}
  validates :start_date, presence: true


  # Paperclip
  has_attached_file :attachment

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

  def self.attributes_for_grid
    [
      :institution_id,
      :name,
      :amount,
      :counterpart_name,
      :start_date,
      :counterpart_info,
      :compliance_deadlines,
      :form_of_contract
    ]
  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.amount, model.counterpart_info, model.compliance_deadlines, model.form_of_contract] }
    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
