# $Id: generator.rb,v 1.17 2004/05/12 18:23:34 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require "qwik/wikitext"
require "qwik/ext_theme"

module Qwik
  class PageGenerator
    def initialize(config, memory)
      @config = config
      @memory = memory
      @data = {}
      @xml = nil
      @g = Qxhtml.new
      @template = "view"
      @head = []
    end
    attr_accessor :template
    attr_reader :head
    attr_reader :xml

    def update(data)
      @data.update(data)
    end

    def generate
      @xml = @memory.template.get(@template)
      @data[:header] = make_head()
      @xml.apply(@data)
      @xml.delete_empty_tag("div", "span", "pre")
      @xml.delete_id
      @xml.add_html_doctype
#     @xml.add_xhtml_doctype
      @xml
    end

    def make_head()
      head = @g.head
      @head.each {|e|
	head << e
      }
      head
    end
  end

  class ServerMemory
    def template
      @template = TemplateFactory.new(@config) if @template.nil?
      @template
    end
  end

  class TemplateFactory
    def initialize(config)
      @config = config
      @templates = {}
    end

    def get(cmd)
#      @templates[cmd] = xml(cmd) # without cache
      @templates[cmd] = xml(cmd) if @templates[cmd].nil?
      @templates[cmd].deep_clone
    end

    private
    def xml(cmd)
      str = open(path(cmd)){|f| f.read }
      str2 = ""
      str.each_line {|line|
	str2 << line.sub(/^\s+/, "")
      }
      str = str2.gsub(/\n/, "")
      xml = REXML::QDocument.new(str)
    end

    def path(cmd)
      path = @config.template_dir
      f = path+"/#{cmd}.html"
      return f if test(?e, f)
      return path+"/view.html"
    end
  end
end
