module JamRuby
  class BroadcastNotification < ActiveRecord::Base

    attr_accessible :title, :message, :button_label, :frequency, :button_url, as: :admin

    has_many :user_views, class_name: 'JamRuby::BroadcastNotificationView', dependent: :destroy

    validates :button_label, presence: true, length: {maximum: 14}
    validates :message, presence: true, length: {maximum: 200}
    validates :title, presence: true, length: {maximum: 50}

    def self.next_broadcast(user)
      self.viewable_notifications(user).limit(1).first
    end

    def self.viewable_notifications(user)
      self.select('broadcast_notifications.*, bnv.updated_at AS bnv_updated_at')
        .joins("LEFT OUTER JOIN broadcast_notification_views AS bnv ON bnv.broadcast_notification_id = broadcast_notifications.id AND (bnv.user_id IS NULL OR (bnv.user_id = '#{user.id}'))")
        .where(['broadcast_notifications.frequency > 0'])
        .where(['bnv.user_id IS NULL OR bnv.active_at < NOW()'])
        .where(['bnv.user_id IS NULL OR broadcast_notifications.frequency > bnv.view_count'])
        .order('bnv_updated_at NULLS FIRST')
    end

    def did_view(user)
      bnv = BroadcastNotificationView
        .where(broadcast_notification_id: self.id, user_id: user.id)
        .limit(1)
        .first

      unless bnv
        bnv = user_views.new()
        bnv.user = user
        bnv.active_at = Time.now - 10
      end

      bnv = user_views.new(user: user) unless bnv
      bnv.view_count += 1
      bnv.save
      bnv
    end

    def frequency_distribution
      @distribution ||= BroadcastNotificationView
        .where(broadcast_notification_id: self.id)
        .group(:view_count)
        .count
    end

  end
end
