# Copyright (C) 2003-2005 Kouichirou Eto, All rights reserved.

$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/csv"

module Qwik
  class Action
    def c_call_plugin(method, param, data)
      args = nil
      args = plugin_parse_args(param) if param && param != ""
      args = [] if args.nil?
      method = "plg_"+method
      begin
	unless self.respond_to?(method)
	  return "nosuch plugin"
	end
	result = self.send(method, *args){data}
	return result
      rescue
	raise if @config.test
	return backtrace_html($!) # act-exception
      end
    end

    def plugin_parse_args(param)
      args = CSVTokenizer.csv_split(param)
      args.collect! {|a|
	case a
	when /\A'(.+)'$/, /^"(.+)"\z/
	  $1
	else
	  a
	end
      }
      args
    end
  end
end

if $0 == __FILE__
  $LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
  require "t/test"
  require "qwik/act-exception"
  $debug = true
end

if $debug
  class TC_ActPlugin < Test::Unit::TestCase
    include TestSession

    def assert(e, s)
      assert_equal(e, @action.plugin_parse_args(s))
    end

    def assert_plugin(e, ar)
      assert_equal(e, @action.c_call_plugin(*ar))
    end

    def test_all
      # test_parse_args
      session
      assert(["a"], "'a'")
      assert(["a"], '"a"')
      assert(["<"], "<")
      #assert(["&lt;"], "'<'") # why?
      assert(["<"], "'<'")
      assert(["a b"], "a b")

      # test_call_plugin
      assert_plugin([:br], ["br", "", ""])
      assert_plugin("nosuch plugin", ["nosuch", "", ""])

      org_test = @config.test
      @config.test = false
      res = @action.c_call_plugin("_qwik_test_for_raise_exception", "", "")
      assert_equal(:h3, res[0][0])
      @config.test = org_test
    end
  end
end
