# represents the gift card you hold in your hand
module JamRuby
  class GiftCard < ActiveRecord::Base

    @@log = Logging.logger[GiftCard]

    JAM_TRACKS_5 = 'jam_tracks_5'
    JAM_TRACKS_10 = 'jam_tracks_10'
    CARD_TYPES =
        [
            JAM_TRACKS_5,
            JAM_TRACKS_10
        ]


    belongs_to :user, class_name: "JamRuby::User"

    validates :card_type, presence: true, inclusion: {in: CARD_TYPES}
    validates :code, presence: true, uniqueness: true

    after_save :check_gifted

    def check_gifted
      if user && user_id_changed?
        if card_type == JAM_TRACKS_5
          user.gifted_jamtracks += 5
        elsif card_type == JAM_TRACKS_10
          user.gifted_jamtracks += 10
        else
          raise "unknown card type #{card_type}"
        end
        user.save!
      end
    end
  end
end
