module BuildWise
  module Publisher
    class Base

      attr_accessor :active
      attr_accessor :name
      attr_accessor :on_event
      
      attr_accessor :logger_io

      def self.formatted_message(state, manager, build, options)
        root_url = "https://agileway.com.au/buildwise"
        begin
          server_url = root_url
        rescue => e
          puts "failed to set root_url in email: #{e}"
        end
        subject =
            case state.current_state
              when :setup
                "BuildWise set up for project (#{manager.scm.current_revision})"
              when :broken
                additional_message = nil
                if state.previous_brokeness and state.current_brokeness
                  additional_message =
                      case
                        when state.previous_brokeness > state.current_brokeness
                          ' but getting better'
                        when state.previous_brokeness < state.current_brokeness
                          ' and getting worse'
                      end
                end
                "Build still broken#{additional_message} (#{manager.scm.current_revision})"


              when :failed
                "Build broken by #{manager.scm.last_author} (#{manager.scm.current_revision})"
              when :revival
                "Build fixed by #{manager.scm.last_author} (#{manager.scm.current_revision})"
              when :successful
                "Build successful (#{manager.scm.current_revision})"
              else
                raise "Unknown build state '#{state.current_state.to_s}'"
            end


        extra_subject = "" # #{options[:publisher, :extra_subject]}
        subject = "[#{options[:application_name]}]#{extra_subject} #{subject}"
        generated_by = "--\nThis email generated by BuildWise v#{BuildWise::VERSION}, #{server_url}"
        body = [manager.scm.last_commit_message]
        if options[:changeset_url]
          body << options[:changeset_url] + manager.scm.current_revision.to_s + "\n"
        end

        body += [manager.setup_script_output,  generated_by].compact



        return subject, body.join("\n")
      end
    end
  end
end