require 'amrita2/template'

module Amrita2View
  class Base
    @@compiled_amrita2_templates = {}

    def initialize( action_view )
      @action_view = action_view
      @action_view.extend(Amrita2::Runtime)
    end

    def render( template, local_assigns={} )
      action_name = @action_view.controller.action_name
      tmpl_method = action_name + "_setup_template"
      tmpl = @@compiled_amrita2_templates[template] ||= 
        if @action_view.respond_to?(tmpl_method)
          @action_view.send(tmpl_method, template)
        else
          t = Amrita2::TemplateText.new(template)
          b = @action_view.instance_eval { binding }
          t.use_erb(b)
          t
        end

      po_method = action_name + "_po"
      po = nil
      if @action_view.respond_to?(po_method)
        po = @action_view.send(po_method)
      else
        po = @action_view.controller
      end             

      tmpl.expand(out="", po)
      out
    rescue
      $!.to_s + $@.join("<br>")
    end
  end
end