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

class BuildWise::Builder::RubyBase < BuildWise::Builder::Base
  attr_reader :output
  attr_accessor :build_log

  def initialize(config, name, cmd = name)
    @config = config
    @cmd = cmd
    @name = name
  end

  def run(active_build = nil)
    puts "About to run..."
    cmd = "#{@config.bin_path}#{choose_exec()} #{@config[:builder, @name.to_sym, :task]}"
    puts "DEBUG command: #{cmd}"
    command_line_output = ::CommandLine.execute(cmd, {:stdout => @build_log, :stderr => @build_log})
    @output = File.read(@build_log)
    successful?
  end

  def old_run

    cmd = "#{@config.bin_path}#{choose_exec()} #{@config[:builder, @name.to_sym, :task]} 2>&1"
    @output = `#{@config.bin_path}#{choose_exec()} #{@config[:builder, @name.to_sym, :task]} 2>&1`
    successful?
  end

  def successful?
    $?.exitstatus == 0 and not @output.include?("#{@cmd} aborted!")
  end

  def brokeness
    if @output =~ /\d+ tests, \d+ assertions, (\d+) failures, (\d+) errors/
      return $1.to_i + $2.to_i
    end
  end

  private
  def choose_exec
    return @cmd
    ext = ['']

    if os() == :windows
      ext << '.bat' << '.cmd'

    end

    puts "DEBUG: cmd = #{@cmd}"
    silence_stream(STDERR) {
      ext.each do |e|
        begin
          out = `#{@config.bin_path}#{@cmd}#{e} --version 2>&1`
          return "#{@cmd}#{e}" if out =~ /#{@cmd}/
        rescue => e
          puts "Error get cmd: #{e}"
        end
      end
    }

    raise "#{@cmd} builder did not find. Make sure that such script exists and have executable permissions."
  end
end