

class BuildWise::Publisher::X10 < BuildWise::Publisher::Base

  attr_accessor :command
  attr_accessor :success_house_unit_code
  attr_accessor :failure_house_unit_code

  def initialize(opts = {})
    @name = "X10"
    @success_house_unit_code = nil
    @failure_house_unit_code = "A1"
  end

  def x10(cmd)
    the_dir = File.expand_path(".")
    FileUtils.chdir("C:\\Program Files\\Home Control")
    begin
      system("x10com32.exe #{cmd}")
    rescue => e
      puts "Error: on sending X10 #{e}"
    ensure
      FileUtils.chdir(the_dir)
    end
  end

  def turn_on_lamp(code)
    x10("#{code} ON") if code
  end

  def turn_off_lamp(code)
    x10("#{code} OFF") if code
  end

  def publish(status, manager, build, options)









    the_build_state = status.current_state
    puts "[DEBUG] X10 status=> #{status.current_state} | #{status.inspect}"
    puts "[DEBUG] X10 manager=> #{manager}"
    puts "[DEBUG] X10 build=> #{build.id}"
    app_name = options[:application_name]
    puts "[DEBUG] X10 options=> #{app_name}"


    if the_build_state =~ /successful/i

      puts "[INFO] Turn off red lamp"
      turn_off_lamp(@failure_house_unit_code)
      puts "[INFO] Turn on green lamp"
      turn_on_lamp(@success_house_unit_code)

    elsif the_build_state =~ /revival/i

      turn_off_lamp(@failure_house_unit_code)
      turn_on_lamp(@success_house_unit_code)

    elsif the_build_state =~ /failed/i || the_build_state =~ /broken/i

      if status.previous_build_successful # just broke the build
        puts "[X10] broken build"
      else
        puts "[X10] still broken"
      end
      puts "[INFO] Failed: Turn on red lamp"
      turn_on_lamp(@failure_house_unit_code)
      puts "[INFO] Failed: Turn off green lamp"
      turn_off_lamp(@success_house_unit_code)
    else
      puts "[X10] unknown build status => |#{the_build_state}|"
    end

  end

end