class UpdateProjectTopicJob < ApplicationJob
  include ProjectsHelper

  queue_as :message

  def perform(project_id)
    return unless $redis_cache.set("UpdateProjectTopicJob:#{project_id}", 1, nx: true, ex: 10.seconds)
    project = Project.find_by(id: project_id)
    return if project.blank?
    begin
      languages = $gitea_client.get_repos_languages_by_owner_repo(project.owner.login, project.identifier)
      puts "#{project.owner.login}/#{project.identifier} get_repos_languages:#{languages}"
      topic_count = 0
      if project.project_category_id.present?
        project_topic = ProjectTopic.find_or_create_by!(name: project.project_category.name.downcase)
        project_topic_ralate = project_topic.project_topic_ralates.find_or_create_by!(project_id: project.id)
        if project_topic.present? && project_topic_ralate.present?
          topic_count +=1
        end
      end
      languages.each do |k, _|
        next if topic_count >= 3
        project_topic = ProjectTopic.find_or_create_by!(name: k.downcase)
        project_topic_ralate = project_topic.project_topic_ralates.find_or_create_by!(project_id: project.id)
        if project_topic.present? && project_topic_ralate.present?
          topic_count +=1
        end
      end
      $redis_cache.del("UpdateProjectTopicJob:#{project_id}")
    rescue => e
      $redis_cache.del("UpdateProjectTopicJob:#{project_id}")
      puts "get_repos_languages: error:#{e.message}"
    end
  end

end