# 执行示例 bundle exec rake "special_commit:load[yystopf, pig]"
# RAILS_ENV=production bundle exec rake "special_commit:load[yystopf, pig]"
#
namespace :special_commit do
  desc "Sync Special Commit to Cache"
  task :load, [:login, :identifier]  => :environment  do |t, args|
    owner = Owner.find_by(login: args.login)
    project = Project.find_by(user_id: owner&.id, identifier: args.identifier)
    if owner.nil? || project.nil?
      puts "====Project is not found.===="
    else 
      puts "====Sync Project: #{owner.real_name}/#{project.name}===="
      puts "====Sync Count Project Self Commit===="
      self_commit_list_result = $gitea_client.get_repos_commits_by_owner_repo(owner.login, project.identifier)
      total_commits = self_commit_list_result[:total_data].to_i
      puts "====Sync Count Project Submodule Commit===="
      entries = $gitea_client.get_repos_contents_by_owner_repo(owner.login, project.identifier)
      entries.each do |entry|
        next if entry["submodule_git_url"].nil? 
        submodule_git_url = entry["submodule_git_url"].gsub(Rails.application.config_for(:configuration)['platform_url'], '').gsub(".git", '')
        real_relative_path = File.expand_path(submodule_git_url, "#{owner.login}/#{project.identifier}").gsub("#{Rails.root}/", '')
        sub_project_owner_login = real_relative_path.split("/")[0]
        sub_project_identifier = real_relative_path.split("/")[1]
        sub_owner = Owner.find_by(login: sub_project_owner_login)
        sub_project = sub_owner.projects.find_by(identifier: sub_project_identifier)
        next if sub_owner.nil? || sub_project.nil?
        sub_commit_list_result = $gitea_client.get_repos_commits_by_owner_repo(sub_project_owner_login, sub_project_identifier)
        total_commits += sub_commit_list_result[:total_data].to_i
        puts "====Sync Count Project Submodule forkproject Commit===="
        sub_project.forked_projects.each do |p|
          forked_project_owner_login = p.owner&.login 
          forked_project_identifier = p.identifier 
          next if forked_project_owner_login.nil? || forked_project_owner_login.nil?
          forked_commit_list_result = $gitea_client.get_repos_commits_by_owner_repo(forked_project_owner_login, forked_project_identifier)
          total_commits += forked_commit_list_result[:total_data].to_i
        end
      end
     
      puts "====Write total commits to cache===="
      $redis_cache.set("ProjectSpecialCommit:#{project.id}", total_commits)
      $redis_cache.expireat("ProjectSpecialCommit:#{project.id}", (Date.today+30.days).to_time.to_i)
    end
  end
end