module UserOnline
  class << self
    def login(user_id)
      set_bit(user_id, 1)
    end

    def logout(user_id)
      set_bit(user_id, 0)
    end

    def set_bit(user_id, flag)
      if !Rails.cache.data.exists(cache_key)
        Rails.cache.data.setbit(cache_key, user_id, flag)
        Rails.cache.data.expire(cache_key, 20 * 60 + 10)
      else
        Rails.cache.data.setbit(cache_key, user_id, flag)
      end
    end

    def count
      if Rails.cache.is_a?(ActiveSupport::Cache::RedisStore)
        Rails.cache.data.bitcount(cache_key)
      else
        0
      end
    end

    def cache_key
      if Rails.cache.is_a?(ActiveSupport::Cache::RedisStore)
        # 10分钟为一段记录用户在线, 统计范围为20分钟内的线用户
        # TODO 更精确时长
        begin_hour = Time.now.beginning_of_hour
        minutes_piece = (Time.now - begin_hour) / 600
        time = begin_hour.since((minutes_piece.to_i - 1) * 600).strftime("%H-%M")
        "online_user_#{time}"
      else
        raise '请配置config.cache_store = redis_store'
      end
    end
  end
end
