# -*- Mode: ruby; indent-tabs-mode: nil -*-
#
#  $Id: template.rb,v 1.14 2003/09/24 00:39:35 hisa Exp $
#
#  Copyright (c) 2003 FUJIMOTO Hisakuni <hisa@fobj.com>
#
#  This program is free software.
#  You can distribute/modify this program under the terms of
#  the GNU Lesser General Public License version 2.
#
require 'tempura/expander'
require 'tempura/source_container'
require 'tempura/source'

module Tempura

  class Template

    class SourceUnspecifiedError < StandardError
    end

    def self.new_with_string(str, charconv = nil, safe_level = nil)
      return self.new(str, charconv, safe_level, true)
    end

    attr_reader :sources, :expander

    def initialize(src = nil, charconv = nil, safe_level = nil, str_p = false)
      @sources = SourceContainer.new
      if src then
        if str_p then
          @sources.default = Source.new_with_string(src, charconv)
        else
          @sources.default = Source.new(src, charconv)
        end
      end
      @expander = Expander.new(safe_level)
    end

    def default_action
      @expander.default_action
    end

    def default_action=(val)
      @expander.default_action = val
    end
      
    def default_event_key
      @expander.default_event_key
    end
    
    def default_event_key=(val)
      @expander.default_event_key = val
    end

    def set(path, key = nil, charconv = nil)
      @sources[key] = Source.new(path, charconv)
    end

    def set_with_string(str, key = nil, charconv = nil)
      @sources[key] = Source.new_with_string(str, charconv)
    end

    def expand(model, key = nil)
      src = @sources[key]
      raise SourceUnspecifiedError if src.nil?
      return @expander.expand_to_string(model, src.fetch_document, src.charconv, true)
    end

    def expand_to_document(model, key = nil)
      src = @sources[key]
      raise SourceUnspecifiedError if src.nil?
      return @expander.expand(model, src.fetch_document, src.charconv, true)
    end

  end
end
