# -*- Mode: ruby; indent-tabs-mode: nil -*-
#
#  $Id: div.rb,v 1.12 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 'div/div'
require 'tempura/source'
require 'tempura/source_container'
require 'tempura/expander'

module Tempura
  class Div < Div::Div

    def self.set_template(path, key = nil, charconv = nil)
      init_variables unless init?
      @sources.set( key, path, charconv )
    end

    def self.reload_template
      init_variables unless init?
      @sources.reload if @sources
    end

    def self.set_safe_level(safe_level)
      init_variables unless init?
      @safe_level = safe_level
    end

    def initialize(session)
      super
      self.class.init_variables
      @template_key = nil
      @expander = Expander.new(safe_level)
      @expander.param_filter do |act, param, bind|
        make_param(act, param)
      end
      @expander.action_filter do |act, param, bind|
        context = eval( "context", bind )
        action(context)    # Div Interface
      end
    end

    def select_template(key)
      @template_key = key
    end

    def to_html_document(context = nil, _key_ = nil)
      _key_ = _key_ || @template_key
      _src_ = sources[_key_]
      return @expander.expand(binding, _src_.fetch_document, _src_.charconv, true)
    end

    def to_html(context = nil, key = nil)
      html_elm = to_html_document(context, key)
      key = key || @template_key
      return sources[key].charconv.from_u8(html_elm.to_s)
    end

    def to_div_document(context = nil, key = nil)
      div = REXML::Document.new
      div.add REXML::Element.new('div')
      div.root.add_attributes( 'class'=>div_class, 'id'=>div_id )
      begin
        child = to_html_document(context, key)
        child = child.root if child.is_a? REXML::Document
      rescue => err
        child = REXML::Element.new('p')
        child.add( REXML::Text.new( "error! #{err}" ) )
      end
      div.root.add( child )
      return div
    end

    def to_div(context = nil, key = nil)
      div_elm = to_div_document(context, key)
      key = key || @template_key
      return sources[key].charconv.from_u8(div_elm.to_s)
    end
    alias :to_s :to_div

    private

    def self.init?
      return @init_p
    end

    def self.init_variables
      unless @init_p then
        @sources = Tempura::SourceContainer.new
        @init_p = true
      end
    end

    def sources
      self.class.instance_eval { @sources }
    end

    def safe_level
      self.class.instance_eval { @safe_level }
    end

  end
end
