require 'drb/drb'
require 'rw-proxy'
require 'tofu/mock'

class RWikiDiv < Div::Div
  set_erb('rwiki.erb')

  def initialize(session)
    super(session)
    @proxy = RWikiProxy.instance
  end

  def path2name(context)
    @proxy.path2name(context.req_path_info)
  end

  def fetch(context)
    name = path2name(context) || 'top'
    @proxy.fetch(name)
  end

  def title(context)
    pg = fetch(context)
    pg.section_prop[:first_heading] || pg.name
  end
  
  def rw_link(name, content = nil)
    content = name unless content
    if content == :heading
      content = @proxy.fetch(name).section_prop[:first_heading]
    end
    "<a href='#{@proxy.escape(name)}'>#{h content}</a>"
  end
  
  def mock_context(name)
    mock = Tofu::MockContext.new
    mock.req_path_info = "/" + @proxy.escape(name)
    mock
  end

  def en_page(name)
    return nil if /\.en$/ =~ name
    en_name = name + ".en"
    page = @proxy.fetch(en_name)
    return nil if page.empty?
    %Q[(<a href="#{@proxy.escape(en_name)}">English</a>|Japanese)]
  end

  def ja_page(name)
    return nil unless /\.en$/ =~ name
    ja_name = name.sub(/\.en$/, '')
    page = @proxy.fetch(ja_name)
    return nil if page.empty?
    %Q[(English|<a href="#{@proxy.escape(ja_name)}">Japanese</a>)]
  end
  
  def babel_link(name)
    en = en_page(name)
    return en if en
    ja = ja_page(name)
    return ja if ja
    ""
  end
  
  def recent_changes(n = -1)
    @proxy.recent_changes[0..n].collect do |name|
      @proxy.fetch(name)
    end
  end
end
