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, 2 * 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)
        # 如设置2分钟内即120秒有请求的用户视为在线, 则最大会统计到4分钟内有活动用户
        # TODO 更精确时长
        begin_hour = Time.now.beginning_of_hour
        minutes_piece = (Time.now - begin_hour) / 120
        time = begin_hour.since((minutes_piece.to_i - 1) * 120).strftime("%H-%M")
        "cache:online_user_#{time}"
      else
        raise '请配置config.cache_store = redis_store'
      end
    end
  end
end
