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

module Qwik
  class Action
    REPLACE_TOC = {
      :h2=>[:ol, 1],
      :h3=>[:ol, 2],
      :h4=>[:ol, 3],
      :h5=>[:ol, 4],
      :h6=>[:ol, 5],
    }

    def toc_inside
      page = @site[@req.base]
      return if page.nil?
      str = page.get_body
      wabisabi = c_parse(str)

      res = TDiaryResolver.new(@config, @site, self)

      tokens = []
      wabisabi.each_tag(:h2, :h3, :h4, :h5, :h6) {|w|
	tag = w[0]
	head = REPLACE_TOC[tag]
	name = res.get_title_name(w)
	if tag == :h2
	  label = res.encode_label(name)
	  link = [:a, {:href=>"#"+label}, name]
	  w = head + [link]
	else
	  w = head + [name]
	end
	tokens << w
      }
      return nil if tokens.length == 0

      parser = TextParser.new
      w = parser.make_tree(tokens).get_single
      w = [[:h5, _("contents")],
	[:div, {:id=>"tocinside"}, w]]
      w
    end

    def plg_toc # deleted
      nil
    end
  end
end

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

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

    def test_toc
      t_add_user
      page = @site.create_new
      page.store("{{toc}}\n*t1\n*t2")
      session("/test/1.html")
      assert_xml([[:h5, "contents"],
		   [:div, {:id=>"tocinside"},
		     [:ol, [:li, [:a, {:href=>"#t1"}, "t1"]],
		       [:li, [:a, {:href=>"#t2"}, "t2"]]]]],
		 "//div[@class='toc']")
    end
  end
end
