module Mimsy
  class TemplateContext
    attr_reader :controller

    def initialize(controller, options = {})
      if defined?(ApplicationHelper)
        extend ApplicationHelper
      end

      extend Mimsy::TemplateHelpers

      @controller    = controller
      @instance_vars = options[:instance_vars] || {}
      @locals        = options[:locals] || {}

      @instance_vars.each do |key, value|
        instance_variable_set(key, value)
      end
    end

    def current_actor
      controller.current_actor
    end

    def request
      controller.request
    end

    def message
      controller.message
    end

    def payload
      controller.payload
    end

    def params
      controller.params
    end

    def child_context(options = {})
      child_options = {}
      child_options[:instance_vars] = @instance_vars.merge(options[:instance_vars] || {})
      child_options[:locals]        = @locals.merge(options[:locals] || {})
      Mimsy::TemplateContext.new(@controller, child_options)
    end

    def method_missing(name, *args, &blk)
      Mimsy.logger.info "method_missing called, args: #{args}, name: #{name}, blk: #{blk}"
      Mimsy.logger.info "locals: #{@locals}"
      if args.size != 0 || blk
        raise NoMethodError, "undefined method `#{name}' for #{self}"
      end

      @locals[name]
    end
  end
end