require 'slack-notifier' # https://github.com/stevenosloan/slack-notifier

class BuildWise::Publisher::Slack < BuildWise::Publisher::Base

  attr_accessor :webhook_url, :channel, :username
  attr_accessor :name

  attr_reader :notifier
  
  def initialize(opts = {})
    @webhook_url = opts[:webhook_url]
    @channel = opts[:channel]
    @username = opts[:username]
    @name = "Slack"
    
    @notifier = ::Slack::Notifier.new @webhook_url, channel: @channel, username: @username
  end

  def publish(status, manager, build, options)

    the_build_state = status.current_state
    project_name = build.project.name

    if the_build_state =~ /successful/i

      message = "#{project_name} is successful."
      @notifier.ping message

    elsif the_build_state =~ /revival/i

      message = "#{project_name} is fixed!"
      @notifier.ping message

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

      if status.previous_build_successful # just broke the build
        message = "#{project_name} is broken!"
        @notifier.ping message
      else
        message = "#{project_name} is still broken"
        @notifier.ping message
      end

    else
      puts "[Slack] unknown build status => |#{the_build_state}|"
    end    

  end
end