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

module Qwik
  class Action
    def act_redirect
      url = @req.query["url"]
      if url
	return c_notice("redirect : #{url}", url){}
      end

      # obsolete
      if @req.unparsed_uri
	url = @req.unparsed_uri
      else
	url = "/"+@req.path_args[0]
      end

      if /\A\/((?:http|https|ftp|file)):\// =~ url
	scheme = $1
	url = url.sub(/\A\/#{scheme}:\//, "#{scheme}:/")
      end

      return c_notice("redirect : #{url}", url){}
    end
  end
end

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

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

    def assert_resolve(e, wabisabi, site=@site)
      session
      res = Qwik::Resolver.new(@config, site, @action)
      w = res.resolve(wabisabi)
      assert_equal(e, w)
    end

    def test_redirect
      session("/test/.redirect?url=http://e.com/")
      assert_text("redirect : http://e.com/", "title")
    end

    def test_all
      # obsolete format
      # test_act_redirect
      session("/http://e.com/")
      assert_text("redirect : http://e.com/", "title")

      session("/http://e.com")
      assert_text("redirect : http://e.com", "title")

      session("/https://e.com/")
      assert_text("redirect : https://e.com/", "title")

      session("/ftp://e.com/")
      assert_text("redirect : ftp://e.com/", "title")

      # test_resolve
      # test_external_link
      assert_wiki([:p, [:a, {:class=>"external", :href=>"http://example.com/"},
		      "http://example.com/"]],
		  "[[http://example.com/]]")
      assert_wiki([:p, [:a, {:href=>"http://example.com/", :class=>"external"},
		      "http://example.com/"]],
		  "http://example.com/")
      assert_wiki([:p,[:a, {:href=>"http://example.com/", :class=>"external"},
		      "t"]],
		  "[[t|http://example.com/]]")

      # test_redirect
      assert_resolve([[:a, {:href=>"http://e.com/", :class=>"external"}, "e"]],
		     [[:a, {:href=>"http://e.com/"}, "e"]])
      page = @site["_SiteConfig"]
      page.store(":redirect:true")
      assert_resolve([[:a, {:href=>"/http://e.com/", :class=>"external"}, "e"]],
		     [[:a, {:href=>"http://e.com/"}, "e"]])

      with_site("e.com"){
	site = Qwik::Site.new(@config, @memory, "e.com")
	assert_resolve([[:a, {:href=>"http://e.com/", :class=>"external"},"e"]],
		       [[:a, {:href=>"http://e.com/"}, "e"]], site)
	#site.close
	site.erase_all
      }
    end

    # can not test this for now...
    def nu_test_with_query
      session("/http://e.com/?q=a&p=b")
      assert_text("redirect : http://e.com/?q=a&p=b", "title")
      #px("//html", 0)
    end

    #def test_redirect
    #  @req.parse_path("/http://e.com/")
    #  assert_equal(["redirect", ["http://e.com/"]], [@req.plugin, @req.path_args])
    #end
  end
end
