module EasyExtensions
  module EasyJobs
    class GitFetcherTask < EasyJob::Task
      def perform(options)
        log_info 'GitFetcherTask excuting...'

        projects = if options[:project_id].present?
                     Array(Project.find_by(id: options[:project_id]))
                   else
                     Project.active.non_templates.sorted.has_module(:repository).preload(options[:fetch_all].present? ? :repositories : :repository).to_a
                   end

        Array(projects).each do |project|
          if options[:fetch_all]
            project.repositories.each do |repository|
              fetch_repository(repository)
            end
          elsif (repository = project.repository)
            fetch_repository(repository)
          end
        end

        log_info 'GitFetcherTask excuted.'
      end

      private

      def fetch_repository(repository)
        log_info "GitFetcherTask fetching #{repository.url}"

        unless system("cd #{repository.url} && git fetch")
          log_warn "Git fetch error"
        end
        repository.fetch_changesets
      end
    end
  end
end