module Support
  class RunLog
    # send logs to ows_cukes_logs
    def self.send_all_logs
      run_dirs = Dir.entries(Support::Paths.logs_root).select do |f|
        File.directory?(File.join(Support::Paths.logs_root, f)) &&
          f != "." &&
          f != ".."
      end
      run_dirs.each do |run_dir|
        run_log = new(run_dir)
        next if run_log.empty?
        run_log.upload_to_s3
      end
    end

    attr_reader :json_files

    def initialize(run)
      @name = run
      @json_files = get_files_from_dir(@name)
    end

    def empty?
      @json_files.empty?
    end

    # Note that this needs AWS credentials to be stored as environment variables
    def upload_to_s3
      fail "no json files to send!" if @json_files.empty?
      @json_files.each do |json_file|
        basename = File.basename(json_file)
        s3_client = Aws::S3::Client.new(region: "us-east-1")
        File.open(json_file) do |file|
          s3_client.put_object(
            bucket: PROFILE.bucket[:qa_bucket_name],
            key: "cucumber-test-logs/#{@name}/#{basename}",
            body: file
          )
        end
      end
    end

    private

    def get_files_from_dir(run)
      dir = File.join(Paths.logs_root, run)
      fail(
        "Run #{run} does not exist in logs directory!"
      ) unless File.exist?(dir)
      Dir["#{dir}/*.json"]
    end
  end
end
