





module TestWise
  class TestResult
    attr_accessor :test_file
    attr_accessor :test_case
    attr_accessor :started_at
    attr_accessor :finished_at
    attr_accessor :successful
    attr_accessor :duration
    attr_accessor :error_trace

    attr_accessor :tester_name
    attr_accessor :target_server
    attr_accessor :tester_machine

    def initialize(attrs)
      @test_file = attrs[:test_file] if attrs[:test_file]
      @test_case = attrs[:test_case] if attrs[:test_case]
      @started_at = attrs[:started_at] if attrs[:started_at]
      @finished_at = attrs[:finished_at] if attrs[:finished_at]
      @successful = attrs[:successful]
      @error_trace = attrs[:error_trace] if attrs[:error_trace]
    end

    def self.from_test_case(test_case)
      a_test_result = TestResult.new({:test_file => test_case.test_file.filename})
      a_test_result.test_case = test_case.name
      a_test_result.duration = test_case.duration
      a_test_result.successful = test_case.successful
      a_test_result.error_trace = "#{test_case.failure}\n#{test_case.error}"
      return a_test_result
    end



  end
end

class BuildWise::Publisher::StoryWise < BuildWise::Publisher::Base

  attr_accessor :url, :release, :token
  attr_accessor :name

  def initialize(opts = {})
    @url = opts[:url]
    @release = opts[:release]
    @token = opts[:token]
    @name = "StoryWise"
  end

  def publish(state, manager, build, options)
    begin
      require 'httpclient'
      client = HTTPClient.new

      puts "Publish Build #{build.id}'s test results to StoryWise: #{@url}"
      puts "storywise release: #{@release} | #{build.all_test_cases.size}"
      test_results = []
      build.all_test_cases.each do |test_case|
        test_results << TestWise::TestResult.from_test_case(test_case)
      end
      puts "storywise: test_results => #{test_results.size}"

      body = {:token => @token, :id => @release, :release => @release, :result_yaml => test_results.to_yaml}
      reply = client.post(@url, body)
      reply_content = reply.body
      reply_content = reply_content.content if reply_content.respond_to?("content")


    rescue => e
      puts "StoryWise publisher failed: #{e}"
      puts e.backtrace
    end

  end
end