require 'test/unit'
require './K5agent'
require 'fileutils'

# Not working.
ARGV.each do |arg|
  if arg.include? 'password'
    #if arg =~ /-password=(.*)/ then $password = $1.to_s.strip end
  end
  if arg.include? 'name'
    #if arg =~ /-name=(.*)/ then $name = $1.to_s.strip end
  end
end

class TestMyAgent < Test::Unit::TestCase

  def setup
    if File.exist?('K5agent.rb')
      FileUtils.copy('K5agent.rb', 'K5agent.rb.save')
      begin 
        FileUtils.copy('K5agent-api.yaml', 'K5agent-api.yaml.save') 
      rescue; end
    end
    @agent = MyAgent.new
  end 

  def test_defining_hello
    actual, s = @agent.send("add pattern /^hello/, hello")
    
    actual, s = @agent.send("hello")

    actual, s = @agent.send(">  def hello(pattern=nil, input=nil)")
    actual, s = @agent.send(">    if @count == nil; @count = 1; return 'I am ready for my first lesson.'; end")
    actual, s = @agent.send(">    return 'Hello again.'")
    actual, s = @agent.send(">  end # method_def")

    actual, s = @agent.send("hello")
    assert_match(/lesson/, actual)

    actual, s = @agent.send("hi is a synonym for hello")
    assert_match(/Okay/, actual)

    actual, s = @agent.send("hi")
    assert_match(/again/, actual)
  end

  def test_show_api
    actual, s = @agent.send("show api")
    assert_match(/ is a synonym for /, actual)
  end

  def test_show_one_method_api
    actual, s = @agent.send("show show_api's api")
    assert_match(/show api/, actual)
  end

  def test_login
    puts "Using login name=#{$name}."
    puts "Using password=#{$password}."
    actual, s = @agent.send("Use the login name #{$name} and the password #{$password}")
    assert_match(/Okay/, actual)
    actual, s = @agent.send("be loggin in to da muthafuckin k$5 an' shit")
    assert_match(/I am logged in/, actual) 
  end

  def teardown
    @agent.logout
    File.delete('K5agent.rb') unless !File.exist?('K5agent.rb.save')
    begin; File.delete('K5agent-api.yaml'); rescue; end
    if File.exist?('K5agent.rb.save')
      FileUtils.copy('K5agent.rb.save', 'K5agent.rb')
      begin; FileUtils.copy('K5agent-api.yaml.save', 'K5agent-api.yaml'); rescue; end
    end
    if File.exist?('K5agent.rb') then File.delete('K5agent.rb.save') end
    if File.exist?('K5agent-api.yaml.save') then File.delete('K5agent-api.yaml.save') end
  end

end
