require File.expand_path File.join(File.dirname(__FILE__), "base.rb")

class BuildWise::Builder::Maven < BuildWise::Builder::Base
  attr_reader :output, :brokeness

  def initialize(config)
    @config = config
    @name = "maven"
  end

  def run(active_build = nil)
    build_dir = @config[:builder, :maven, :build_dir]
    Dir.chdir(build_dir) if build_dir

    cmd = @config[:builder, :maven, :cmd] || 'mvn'

    tasks, task_names = build_tasks("test")
    result = false
    tasks.each_with_index do |task, idx|
      task_name = task_names[idx] rescue ""
      if @build_log
        full_cmd = cmd + " " + task
        puts "Running full maven command";
        File.open(@build_log, "a") { |io| io.write("####{task_name_for_display(task_name)}###\n") }
        update_build_stage(active_build, task_name)
        exit_value = ::CommandLine.execute(full_cmd, {:stdout => @build_log, :stderr => @build_log})
        puts "XXXX: Maven Exit Value: |#{exit_value}|"
        @output = File.read(@build_log)
      else
        @output = `#{cmd} #{task} 2>&1`
      end
      result = successful?
    end
    puts "output: #{output}"
    puts "maven successful: #{result}"
    return result
  end

  def successful?
    $?.exitstatus == 0 and not @output.include?('[ERROR] BUILD FAILURE')
  end

  private

  def system_properties
    properties = []
    system_properties = @config[:builder, :maven2, :system_properties]
    if system_properties
      system_properties.each do |p|
        properties << %Q(-D#{p[0]}="#{p[1]}")
      end
    end
    properties.join(' ')
  end

  def settings
    settings_file = @config[:builder, :maven2, :settings]
    if settings_file
      return "-s #{settings_file}"
    else
      return ''
    end
  end

  def add_error_information
    str = @output
    @output = ''
    @brokeness = 0
    while str =~ / <<< FAILURE!$/
      @brokeness += 1
      s = $'

      $` =~ /^(.|\n)*Running (.*)$/
      failed_class = $2
      @output << $` << $& << ' <<< FAILURE!'
      surefire_report_filename = "#{@config[:application_root]}/target/surefire-reports/#{failed_class}.txt"
      @output << "\n" << IO.readlines(surefire_report_filename)[4..-1].join.lstrip if test(?e, surefire_report_filename)
      str = s
    end
    @output << str
  end
end