require 'mail'




if RUBY_VERSION =~ /1\.8\.\d/

  require 'buildwise/publisher/netsmtp_tls_fix'
end

class BuildWise::Publisher::Mail < BuildWise::Publisher::Base

  attr_accessor :recipients
  attr_accessor :sender
  attr_accessor :delivery_method
  attr_accessor :address
  attr_accessor :port
  attr_accessor :domain
  attr_accessor :user_name
  attr_accessor :password
  attr_accessor :authentication
  attr_accessor :enable_starttls_auto

  attr_accessor :name

  def initialize(opts = {})
    @name = "Email"
    @enable_starttls_auto = true


    @sender = opts[:sender]
    @sender ||= "mailer@buildwise.agileway.net"

    @delivery_method = opts[:delivery_method] || :smtp
    @delivery_method = @delivery_method.to_sym if @delivery_method.class == String
  end

  def publish(status, manager, build, options)

    raise "There is no recipients provided for mail publisher" unless @recipients

    puts "#{Time.now} [DEBUG] state => #{status.current_state}"
    begin

      the_subject, the_body = BuildWise::Publisher::Base.formatted_message(status, manager, build, options)
      the_recipients = @recipients
      the_from = @sender
      raise "Please specify recipient addresses for application '#{options[:application_name]}'" unless the_recipients

      mail = Mail.new do
        to the_recipients
        from the_from
        subject the_subject
        body the_body
      end

      mail.deliver

    rescue => e
      puts "#{Time.now} [WARN] Failed to deliver email: #{e}, #{e.backtrace}"
      raise e
    end
  end

  def configure













    if @authentication && @authentication.strip.empty?
      @authentication = nil
    end
    
    options = {
        :address => @address,
        :port => @port.to_i,
        :domain => @domain,
        :user_name => @user_name || ENV['GMAIL_USER'],
        :password => @password || ENV['GMAIL_PASSWORD'],
        :authentication => @authentication,
        :enable_starttls_auto => true
    }
    
    @delivery_method ||= :smtp

    Mail.defaults do
      delivery_method @delivery_method, options
    end
  end

  private
















end