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

class BuildWise::Builder::Ant < BuildWise::Builder::Base

  attr_reader :output
  attr_accessor :build_log

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

  def run_task(build_step, log_file)
    task_name = build_step.name
    target = build_step.task


    cmd = "ant"    

    if log_file


      full_cmd = cmd + " " + target.to_s      
      begin
        puts "[ant] #{Time.now} [INFO] Run Ant task '#{target.to_s}'"


        exit_value = ::CommandLine.execute(full_cmd.split(" "), {:stdout => log_file, :stderr => log_file, :env => @config.build_environment_variables})
      

        @output = File.read(log_file)
      ensure
        
      end
    else
      puts "#{Time.now} [DEBUG] Rake Exit Value from execution #{cmd}"
      @output = `#{cmd} #{target} 2>&1`
    end
    
    result = successful?
    raise "Failed on task: #{target}" unless result
    return result      
  end
  
=begin
  def run(active_build = nil)
    puts "[INFO] Ant running a build #{active_build.id}"

    begin
      build_dir = @config[:builder, :ant, :build_dir]
      default_task = @config[:builder, :ant, :target]
    rescue => e
      default_task = ""
    end

    Dir.chdir(build_dir) if build_dir
    cmd = @config.builder_cmd || 'buildwise_ant'

    tasks, task_names = build_tasks(default_task || "")

    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 ant 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})

        @output = File.read(@build_log)
      else
        @output = `#{cmd} #{task} 2>&1`
      end
      result = successful?
    end
    puts "ant successful: #{result}"
    return result
  end
=end
  
  def successful?
    puts "[ant] Exit Status: |#{$?.exitstatus}|#{$?.exitstatus == 0 && @output =~ /BUILD\sSUCCESSFUL/}"
    $?.exitstatus == 0 and @output.include?("BUILD SUCCESSFUL")

  end

  def brokeness
    return nil
  end
end