require 'div/div'
require 'div/tofusession'
require 'rwiki-div'
require 'rwtodo'
require 'theme-div'
require 'tofu/mock'

class RWikiViewSession < Div::TofuSession
  def initialize(bartender, hint=nil)
    super(bartender, hint)
    @base = BaseDiv.new(self)
  end

  def do_GET(context)
    update_div(context)
    context.res_header('content-type', 'text/html; charset=euc-jp')
    context.res_body(@base.to_html(context))
  end
end

class RWikiViewSession

  SNAPSHOT_DIR = '/home/mas/labo/htdocs/mesh/ruby'
  # SNAPSHOT_DIR = '.'

  class Traverser
    def initialize(rwiki)
      @rwiki = rwiki
      @foot_print = {}
    end
    
    def traverse(name, &block)
      return if @foot_print.include?(name)
      pg = @rwiki.page(name)
      @foot_print[name] = pg
      yield(name)
      pg.links.each do |child|
	traverse(child, &block)
      end
    end
  end

  class BaseDiv < Div::Div
    set_erb('base.erb')

    def initialize(session)
      super(session)
      @theme = ThemeDiv.new(session, self)
      @rwiki = RWikiDiv.new(session)
      @todo = RWikiToDoDiv.new(session)
    end
  
    def do_snapshot(context, params)
      proxy = RWikiProxy.instance
      root = proxy.path2name(context.req_path_info)
      traverser = Traverser.new(proxy.rwiki)
      traverser.traverse(root) do |name|
	filename = proxy.escape(name)
	path = File.join(SNAPSHOT_DIR, filename)
	File.open(path, 'w') do |fp|
	  fp.write(static_page(name))
	  fp.close
	end
      end
    end

    def static_page(name)
      mock = @rwiki.mock_context(name)
      to_html(mock)
    end
  end
end

if __FILE__ == $0
  require 'drb/drb'
  require 'tofu/proxy'
  require 'rinda/ring'

  DRb.start_service
  
  tofu = Tofu::Bartender.new(RWikiViewSession)

  ts = Rinda::RingFinger.primary

  tuple = ts.read([:name, :Tofulet, nil, nil])
  webrick = tuple[2]
  webrick.mount('/static', DRbObject.new(tofu))

  while gets
    Div.reload_erb
  end
end
