class OfciaComplaint < ActiveRecord::Base
  attr_accessible :name, :complaint_at, :received, :phone, :cellular, :email, :twitter, :facebook, :anonymous, :content

  # associations
  belongs_to :user
  has_and_belongs_to_many :institutions
  
  # validations
  validates :name, :complaint_at, :received, :anonymous, :content, presence: true

  # callbacks
  before_create :set_correlative
  after_create :send_ofcia_complaint

  # enumerated attributes
  enumerated_attribute :received, %w(phone email attendance twitter facebook) do
    label phone: I18n.t('enum.ofcia_complaint.received.phone')
    label email: I18n.t('enum.ofcia_complaint.received.email')
    label attendance: I18n.t('enum.ofcia_complaint.received.attendance')
    label twitter: I18n.t('enum.ofcia_complaint.received.twitter')
    label facebook: I18n.t('enum.ofcia_complaint.received.facebook')
  end
  enumerated_attribute :anonymous, %w(yes no) do
    label yes: I18n.t('enum.ofcia_complaint.anonymous.affirmative')
    label no: I18n.t('enum.ofcia_complaint.anonymous.negative')
  end

  # delegates
  delegate :name, :email, to: :user, allow_nil: true, prefix: true


  private
    def set_correlative
      self.correlative = "D-#{Date.current.strftime('%Y%m%d')}-#{'%03i' % (OfciaComplaint.count + 1)}"
    end

    def send_ofcia_complaint
      UserMailer.ofcia_complaint_notify(self).deliver
    end
end
