class BuildWise::Publisher::Tplink < BuildWise::Publisher::Base

  attr_accessor :command
  attr_accessor :success_device
  attr_accessor :failure_device

  def initialize(opts = {})
    require 'tp_link'
    
    @name = "TP-Link Smart Plug"
    @success_device = nil
    @failure_device = nil
    

    @smart_home = TPLink::SmartHome.new('user' => ENV["TP_LINK_CLOUD_ACCOUNT_USER"],'password' => ENV["TP_LINK_CLOUD_ACCOUNT_PASS"])
  end


  def switch_plug(device_name, on_or_off)
    device = @smart_home.find(device_name)
    if device     
      if on_or_off
        device.on
      else
        device.off
      end
    end
  end

  def turn_on(device)
    switch_plug(device, true) if device
  end

  def turn_off(device)
    switch_plug(device, false) if device
  end

  def publish(status, manager, build, options)

    the_build_state = status.current_state
    puts "#{Time.now} [DEBUG] TP-Link Plug status=> #{status.current_state} "
    puts "#{Time.now} [DEBUG] TP-Link Plug build=> #{build.id}"
    app_name = options[:application_name]
    puts "#{Time.now} [DEBUG] TP-Link Plug options=> #{app_name}"


    if the_build_state =~ /successful/i

      puts "#{Time.now} [INFO] Turn off red lamp"
      turn_off(@failure_device)
      puts "#{Time.now} [INFO] Turn on green lamp"
      turn_on(@success_device)

    elsif the_build_state =~ /revival/i

      turn_off(@failure_device)
      turn_on(@success_device)

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

      if status.previous_build_successful # just broke the build
        puts "#{Time.now} [INFO] [TP-Link] broken build"
      else
        puts "#{Time.now} [INFO] [TP-Link] still broken"
      end
      puts "[INFO] Failed: Turn on red lamp"
      turn_on(@failure_device)
      puts "[INFO] Failed: Turn off green lamp"
      turn_off(@success_device)
    else
      puts "#{Time.now} [INFO] [TP-Link] unknown build status => |#{the_build_state}|"
    end

  end

end