class BuildWise::Publisher::HttpCallback < BuildWise::Publisher::Base

  attr_accessor :webhook_url

  def initialize(opts = {})
    @webhook_url = opts[:webhook_url]
    @name = "Http Callback"
  end

  def notify_success()
    begin
      require 'httparty'
      HTTParty.post(@webhook_url, body: { result: 'success'})
    rescue => e
      puts "#{Time.now} [INFO] [HttpCallback] Failed to notify success"
    end
  end

  def notify_failure()
    begin
      require 'httparty'      
      HTTParty.post(@webhook_url, body: { result: 'failed' })
    rescue => e
      puts "#{Time.now} [INFO] [HttpCallback] Failed to notify failure"
    end
  end

  def publish(status, manager, build, options)

    the_build_state = status.current_state
    app_name = options[:application_name]


    if the_build_state =~ /successful/i

      notify_success()

    elsif the_build_state =~ /revival/i

      notify_success()

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

      if status.previous_build_successful # just broke the build
        puts "#{Time.now} [INFO] [HttpCallback] broken build"
      else
        puts "#{Time.now} [INFO] [HttpCallback] still broken"
      end
      notify_failure()
    else
      puts "#{Time.now} [INFO] [HttpCallback] unknown build status => |#{the_build_state}|"
    end

  end

end