# 项目日活跃度计算存储
class Cache::V2::ProjectDateRankService < ApplicationService 
  attr_reader :project_id, :rank_date, :visits, :praises, :forks, :issues, :closed_issues, :pullrequests, :commits
  attr_accessor :project_common

  def initialize(project_id, rank_date=Date.today, params={})
    @project_id = project_id
    @rank_date = rank_date
    @visits = params[:visits]
    @watchers = params[:watchers]
    @praises = params[:praises]
    @forks = params[:forks]
    @issues = params[:issues]
    @closed_issues = params[:closed_issues]
    @pullrequests = params[:pullrequests]
    @commits = params[:commits]
  end

  def read 
    project_rank
  end

  def call 
    set_project_rank
  end

  private 
  def project_rank_key
    "v2-project-rank-#{@rank_date.to_s}"
  end

  def project_rank_statistic_key 
    "v2-project-statistic:#{@project_id}-#{@rank_date.to_s}"
  end

  def project_rank
    $redis_cache.zscore(project_rank_key, @project_id)
  end

  def set_project_rank
    if @visits.present?
      $redis_cache.zincrby(project_rank_key, @visits.to_i * 1, @project_id) 
      $redis_cache.hincrby(project_rank_statistic_key, "visits", @visits.to_i) 
    end
    if @watchers.present?
      $redis_cache.zincrby(project_rank_key, @watchers.to_i * 5, @project_id) 
      $redis_cache.hincrby(project_rank_statistic_key, "watchers", @watchers.to_i) 
    end
    if @praises.present?
      $redis_cache.zincrby(project_rank_key, @praises.to_i * 5, @project_id) 
      $redis_cache.hincrby(project_rank_statistic_key, "praises", @praises.to_i) 
    end
    if @forks.present?
      $redis_cache.zincrby(project_rank_key, @forks.to_i * 10, @project_id) 
      $redis_cache.hincrby(project_rank_statistic_key, "forks", @forks.to_i) 
    end
    if @issues.present?
      $redis_cache.zincrby(project_rank_key, @issues.to_i * 5, @project_id) 
      $redis_cache.hincrby(project_rank_statistic_key, "issues", @issues.to_i) 
    end
    if @closed_issues.present? 
      $redis_cache.hincrby(project_rank_statistic_key, "closed_issues", @closed_issues.to_i) 
    end
    if @pullrequests.present?
      $redis_cache.zincrby(project_rank_key, @pullrequests.to_i * 10, @project_id) 
      $redis_cache.hincrby(project_rank_statistic_key, "pullrequests", @pullrequests.to_i) 
    end
    if @commits.present? 
      $redis_cache.zincrby(project_rank_key, @commits.to_i * 5, @project_id)
      $redis_cache.hincrby(project_rank_statistic_key, "commits", @commits.to_i) 
    end

    $redis_cache.zscore(project_rank_key, @project_id)

    # 设置过期时间（一个月）
    $redis_cache.expireat(project_rank_key, (@rank_date+30.days).to_time.to_i)
    $redis_cache.expireat(project_rank_statistic_key, (@rank_date+30.days).to_time.to_i)
  end
end