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

    @@log = Logging.logger[PosaCard]

    JAM_TRACKS_5 = 'jam_tracks_5'
    JAM_TRACKS_10 = 'jam_tracks_10'
    JAM_CLASS_4 = 'jam_class_4'
    JAM_CLASS_2 = 'jam_class_2'
    CARD_TYPES =
        [
            JAM_TRACKS_5,
            JAM_TRACKS_10,
            JAM_CLASS_4,
            JAM_CLASS_2
        ]


    belongs_to :user, class_name: "JamRuby::User"
    belongs_to :retailer, class_name: "JamRuby::Retailer"
    belongs_to :lesson_package_type, class_name: "JamRuby::LessonPackageType"

    has_many :posa_card_purchases, class_name: 'JamRuby::PosaCardPurchase'
    has_one :lesson_package_purchase, class_name: 'JamRuby::LessonPackagePurchase'
    has_one :jam_track_right, class_name: "JamRuby::JamTrackRight"


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

    after_save :check_attributed

    validate :already_activated
    validate :retailer_set
    validate :already_claimed
    validate :user_set
    validate :must_be_activated
    validate :within_one_year

    def is_amazon_posa_card?
      lesson_package_type.is_amazon?
    end
    def is_lesson_posa_card?
      self.is_lesson
    end

    def self.find_by_amazon_code(code)
      PosaCard.where('code ilike ?', code).where('lesson_package_type_id in (?)', LessonPackageType::AMAZON_PACKAGES).first
    end

    def already_activated
      if activated_at && activated_at_was && activated_at_changed?
        if retailer && retailer_id == retailer_id_was
          self.errors.add(:activated_at, 'already activated. Please give card to customer. Thank you!')
        else
          self.errors.add(:activated_at, 'already activated by someone else.  Please contact support@jamkaazm.com')
        end
      end
    end

    def within_one_year
      if user && claimed_at && !claimed_at_was && claimed_at_changed?
        if !user.can_claim_posa_card
          self.errors.add(:claimed_at, 'was within 1 year')
        end
      end
    end

    def already_claimed
      if claimed_at && claimed_at_was && claimed_at_changed?
        self.errors.add(:claimed_at, 'already claimed')
      end
    end

    def retailer_set
      if activated_at && !retailer
        self.errors.add(:retailer, 'must be specified')
      end
    end

    def user_set
      if claimed_at && !user
        self.errors.add(:user, 'must be specified')
      end
    end

    def must_be_activated
      if claimed_at && !preactivate && !activated_at
        self.errors.add(:activated_at, 'must already be set')
      end
    end

    def check_attributed
      if user && user_id_changed?
        if card_type == JAM_TRACKS_5
          user.gifted_jamtracks += credits
        elsif card_type == JAM_TRACKS_10
          user.gifted_jamtracks += credits
        elsif is_lesson_posa_card?
          user.jamclass_credits += credits
        else
          raise "unknown card type #{card_type}"
        end
        user.save!
      end
    end

    def product_info
      price = nil
      plan_code = nil

      if card_type == JAM_TRACKS_5
        price = 9.99
        plan_code = 'posa-jamtracks-5'
      elsif card_type == JAM_TRACKS_10
        price = 19.99
        plan_code = 'posa-jatracks-10'
      elsif is_lesson_posa_card?
        price = lesson_package_type.price
        plan_code = "posa-jamclass-#{credits}"
      else
        raise "unknown card type #{card_type}"
      end
      {price: price, quantity: 1, marked_for_redeem: false, plan_code: plan_code}
    end

    def self.activate(posa_card, retailer)
        Sale.posa_activate(posa_card, retailer)
    end

    def activate(retailer)
      self.activated_at = Time.now
      self.retailer = retailer

      self.save
    end

    def has_been_purchased(create_purchase)
      if !purchased

        #release flag on user account indicating they need to buy this card
        user.lesson_package_needs_purchase = nil
        user.save

        # indicate this has been purchased
        self.purchased = true
        self.save

        if is_lesson_posa_card? && create_purchase
          LessonPackagePurchase.create(user, nil, lesson_package_type, nil, nil, self)
        end
      end
    end

    def claim(user)
      self.user = user
      self.claimed_at = Time.now

      if self.save
        if user.errors.any?
          # happens on signup if bad email etc
          return
        end

        UserWhitelist.card_create(user, 'posa')

        if !preactivate
          SaleLineItem.associate_user_for_posa(self, user)
        end

        if requires_purchase
          # this is a flag on the account that makes it so the user can't buy any TD's on the payment page until they clear this up, because we've given them credits
          user.lesson_package_needs_purchase = self.lesson_package_type
          user.save
        end

        # when you claim a POSA card, you are also making a LessonPackagePurchase
        if is_lesson_posa_card?

          GuitarCenter.post_posa_claim(self)

          if purchased
            LessonPackagePurchase.create(user, nil, lesson_package_type, nil, nil, self)
          end
        end
      end
    end

    def short_display
      if card_type == JAM_TRACKS_5
        'JT-5'
      elsif card_type == JAM_TRACKS_10
        'JT-10'
      elsif is_lesson_posa_card?
        "JC-#{credits}"
      else
        raise "unknown card type #{card_type}"
      end
    end
    def to_s
      "POSA #{short_display} #{code}"
    end
  end
end
