module Slackistrano
  class CustomMessaging < Messaging::Base

    STAGE_WRAPPER = '*'.freeze

    # Tweaks deployment messages slightly. Documentation:
    # https://github.com/phallstrom/slackistrano#customizing-the-messaging
    # https://api.slack.com/docs/message-attachments
    # https://api.slack.com/docs/message-formatting

    def deployer
      name = `git config user.name`.strip
      name = super if name.empty?
      name
    end

    def stage
      "#{STAGE_WRAPPER}#{super}#{STAGE_WRAPPER}"
    end

    def payload_for_starting
      payload = super
      payload[:text] = ":hand: #{deployer} has started #{stage} deployment"
      payload
    end

    def payload_for_updating
      payload = super
      payload[:text] = ":rocket: #{payload[:text]}"
      payload
    end

    def payload_for_updated
      {
        attachments: [{
          color: 'good',
          fields: [{
            title: 'Environment',
            value: stage.tr(STAGE_WRAPPER, ''),
            short: true,
          }, {
            title: 'Branch',
            value: branch,
            short: true,
          }, {
            title: 'Deployed by',
            value: deployer,
            short: true,
          }, {
            title: 'Time',
            value: elapsed_time,
            short: true,
          }],
          fallback: super[:text],
        }],
        text: ':star2: Deployed successfully!',
      }
    end

    def payload_for_failed
      payload = super
      payload[:text] = ":boom: #{payload[:text]}"
      payload
    end

    def payload_for_reverting
      payload = super
      payload[:text] = ":warning: #{payload[:text]}"
      payload
    end

    def payload_for_reverted
      payload = super
      payload[:text] = ":recycle: #{payload[:text]}"
      payload
    end

  end
end
