require 'amrita2/template'
require 'gettext/rgettext'

module Amrita2
  module Core
    class CompoundElement # :nodoc: all
      def get_erb_source
        @children.collect do |c|
          c.get_erb_source
        end.join("\n")
      end
    end

    class ErbNode # :nodoc: all
      def get_erb_source
        return @node.to_s
      end
    end

    class DynamicElement # :nodoc: all
      def get_erb_source
        @children.collect do |c|
          c.get_erb_source
        end.join("\n")
      end
    end

    class CommentNode # :nodoc: all
      def get_erb_source
        ""
      end
    end

    class RootElement < DynamicElement # :nodoc: all
      attr_accessor :text_domain
      compile_old = self.instance_method(:compile)

      define_method(:compile) do |cg|
        cg.code("bindtextdomain(#{@text_domain.inspect})")
        compile_old.bind(self).call(cg)
      end

    end

    class Template
      attr_accessor :text_domain
      def compile_for_gettext
        setup
      end

      def get_erb_source_for_gettext
        setup
        @root.get_erb_source
      end
    end
  end

  module GetTextBridge # :nodoc: all
    class TextNodeForGetText < Core::StaticNode
      def dynamic?
        true
      end

      def render_me(cg)
        #text = @node.to_s.strip

        # to keep &nbsp;
        text = ""
        @node.output(text, :preserve=>true)
        text.strip!
        cg.put_string_expression("_(#{text.inspect}) % $_") if text != ""
      end
      def get_erb_source
        return ""
      end
    end
  end

  module Filters
    class GetTextFilter < Filters::Base
      def parse_node(de, node)
        case node
        when Hpricot::CData
          super
        when Hpricot::Text
          Amrita2::GetTextBridge::TextNodeForGetText.new(de, node)
        else
          super
        end
      end
    end
  end

  module GetTextParser # :nodoc: all
    include Amrita2
    include Amrita2::GetTextBridge

    module_function
    def target?(file)
      File.extname(file) == '.a2html' || File.extname(file) == '.a2'
    end

    def parse(file, ary)
      t = Template.new(File::open(file).read) do |e, src, filters|
        filters << Filters::GetTextFilter.new
      end


      src = t.compile_for_gettext
      RubyParser.parse_lines(file, [src], ary)
      src = t.get_erb_source_for_gettext
      erb = ERB.new(src).src.split(/$/)
      RubyParser.parse_lines(file, erb, ary)
      ary.collect do |msgid, fnameandline|
        [msgid, fnameandline.gsub(/\d+$/, "-")]
      end
    end
  end
end

GetText::RGetText.add_parser(Amrita2::GetTextParser)
