require 'liquid'

#NOTE: added this file as a liquid proof of concept.

module Thingy
  module Liquid
    module Filters
      module Common
        def cprepend(text, before)
          text.to_s.length > 0 ? "#{before}#{text}" : ''
        end

        def cappend(text, after)
          text.to_s.length > 0 ? "#{text}#{after}" : ''
        end

        def cwrap(text, before, after)
          text.to_s.length > 0 ? "#{before}#{text}#{after}" : ''
        end

        def join(items, separator = ', ')
          [*items].join(separator)
        end

        def humanize(symbol)
          symbol.to_s.gsub('_', ' ')
        end

        def ljust(text, len, char = ' ')
          text.to_s.ljust(len, char)
        end
      end

      module Topic
        def attribute(topic, type)
          topic.instance_variable_get(:@object)[type]
        end
      end
    end

    #1. pull in a template (via association?)
    #2. pull in a layout (via association?)
    #3. both template and layout associations will be scoped to avoid refering to themselves within the template
    module Renderers
      module Topic
        def render
          playground = <<-HERE
            {% for name in topic.names -%}
              {{name.type | humanize }} => {{name.value}}{% unless forloop.last %},{% endunless %}
            {% endfor -%}
            {{topic | attribute: 'age' | cwrap: '<age>', '</age>'}}
          HERE
          body = <<-HERE
            *{{topic.name}}*
            {% for key in topic.used_keys -%}{{key | humanize | ljust: 20 }}: {{topic | attribute: key | join }}
            {% endfor -%}
          HERE
          ::Liquid::Template.parse(body).render({'topic' => self}, :filters => [Thingy::Liquid::Filters::Common, Thingy::Liquid::Filters::Topic])
        end
      end
    end
  end

  Name.class_eval do
    liquid_methods :type, :value
  end

  Topic.class_eval do
    liquid_methods :name, :names, :age, :occurrence, :keys, :used_keys
    include Thingy::Liquid::Renderers::Topic
  end
end
