module Parser
  
  def parser_context(page, attributes = {})
    Radius::Context.new do |c|
      c.define_tag 'snippet' do |tag|
        snippet = Snippet.first(:conditions => {:name => tag.attr['name']})
        if snippet
          snippet.content
        else
          t('nothing')
        end
      end
      c.define_tag 'language_bar' do
        @site.in_use_locales.map{ |locale|
          lang = I18nVariable.first(:conditions => {:key => locale})[locale]
          if I18n.locale.to_s.eql?(locale)
            lang
          else
            "<a href='?locale=#{locale}'>#{lang}</a>"
          end
        }.join(' | ')
      end
      c.define_tag 'locale' do |tag|
        case attributes[:locale]
          when 'create'
            var = I18nVariable.new(:key => (tag.attr['name'] rescue nil), :document_class => 'Text')
            @site.valid_locales.each do |locale|
              var[locale] = tag.attr[locale] rescue nil
            end
            var.save!
            res = ''
            res << "<r:locale id='#{var.id}' " 
            res << "name='#{var.key}' " if var.key
            @site.valid_locales.each do |locale|
              res << "#{locale}='#{var[locale]}' "
            end
            res << '/>'
          when 'show'
            var = I18nVariable.find(tag.attr['id'])
            res = ''
            res << "<r:locale " 
            res << "name='#{var.key}' " if var.key
            @site.valid_locales.each do |locale|
              res << "#{locale}='#{var[locale]}' "
            end
            res << '/>'
          when 'destroy'
            var = I18nVariable.find(tag.attr['id'])
            var.destroy
          else
            tag.attr[I18n.locale.to_s] rescue nil
        end
      end
      c.define_tag 'css' do |tag|
        assets = Asset.any_in(:filename => tag.attr['name'].split(',').map(&:strip))
        res = ''
        assets.each do |asset|
          res << "<link href='#{asset.data.file.url}' rel='stylesheet' type='text/css' /> " if asset.data.file.content_type.eql?('text/css')
        end
        res
      end
      c.define_tag 'image' do |tag|
        asset = Asset.find(tag.attr['id'])
        if asset
          res = "<img src=#{asset.data.file.url} "
          tag.attr.each do |l|
            res << "#{l[0]}='#{l[1]}' "
          end
          res << '>'
        end
      end
      c.define_tag 'layout_part' do |tag|
        ret = ''
        ret << "<div id='#{tag.attr['name']}'>"
        ret << page.page_parts.detect{ |p| p.name.to_s == tag.attr['name'].to_s }.content rescue ''
        ret << tag.expand
        ret << '</div>'
      end
    end
  end
  
  def parse_content(page_content, attributes = {})
    context = parser_context(page_content, attributes)
    parser = Radius::Parser.new(context, :tag_prefix => 'r')
    parser.parse(page_content)
  end
  
  def parse_page(page)
    if page._type == 'Page'
      layout_content = page.layout.content 
      context = parser_context(page)
      parser = Radius::Parser.new(context, :tag_prefix => 'r')
      parser.parse(parser.parse(layout_content))
    end
  end
  
  def parse_page_edit(page)
    if page._type == 'Page'
      layout_content = page.layout.content 
      context = parser_context_edit(page)
      parser = Radius::Parser.new(context, :tag_prefix => 'r')
      parser.parse(parser.parse(layout_content))
    end
  end
  
  def parser_context_edit(page, attributes = {})
    Radius::Context.new do |c|
      c.define_tag 'snippet' do |tag|
        snippet = Snippet.first(:conditions => {:name => tag.attr['name']})
        if snippet
          snippet.content
        else
          t('nothing')
        end
      end
      c.define_tag 'language_bar' do
        @site.in_use_locales.map{ |locale|
          lang = I18nVariable.first(:conditions => {:key => locale})[locale]
          if I18n.locale.to_s.eql?(locale)
            lang
          else
            "<a href='?locale=#{locale}'>#{lang}</a>"
          end
        }.join(' | ')
      end
      c.define_tag 'locale' do |tag|
        case attributes[:locale]
          when 'create'
            var = I18nVariable.new(:key => (tag.attr['name'] rescue nil), :document_class => 'Text')
            @site.valid_locales.each do |locale|
              var[locale] = tag.attr[locale] rescue nil
            end
            var.save!
            res = ''
            res << "<r:locale id='#{var.id}' " 
            res << "name='#{var.key}' " if var.key
            @site.valid_locales.each do |locale|
              res << "#{locale}='#{var[locale]}' "
            end
            res << '/>'
          when 'show'
            var = I18nVariable.find(tag.attr['id'])
            res = ''
            res << "<r:locale " 
            res << "name='#{var.key}' " if var.key
            @site.valid_locales.each do |locale|
              res << "#{locale}='#{var[locale]}' "
            end
            res << '/>'
          when 'destroy'
            var = I18nVariable.find(tag.attr['id'])
            var.destroy
          else
            tag.attr[I18n.locale.to_s] rescue nil
        end
      end
      c.define_tag 'css' do |tag|
        assets = Asset.any_in(:filename => tag.attr['name'].split(',').map(&:strip))
        res = ''
        assets.each do |asset|
          res << "<link href='#{asset.data.file.url}' rel='stylesheet' type='text/css' /> " if asset.data.file.content_type.eql?('text/css')
        end
        res
      end
      c.define_tag 'image' do |tag|
        asset = Asset.find(tag.attr['id'])
        if asset
          res = "<img src=#{asset.data.file.url} "
          tag.attr.each do |l|
            res << "#{l[0]}='#{l[1]}' "
          end
          res << '>'
        end
      end
      c.define_tag 'layout_part' do |tag|
        part = page.page_parts.detect{ |p| p.name.to_s == tag.attr['name'].to_s }
        ret = ''
        ret << "<div id='#{tag.attr['name']}'"
        ret << " part_id='#{part.id}'" if part
        ret << " class='editable'" if part
        ret << " style='border:solid 1px; margin:5px; padding:5px;'>"
        ret << "<div class='edit_link' style='display:none'>" if part
        ret << " <a href='#{edit_admin_page_part_path(part.id)}' class='nav'>#{t(:edit)}</a>" if part
        ret << '</div>' if part
        ret << part.content rescue ''
        ret << tag.expand
        ret << '</div>'
      end
    end
  end
  
  def self.included(base)
    base.send :helper_method, :parse_page if base.respond_to? :helper_method
    base.send :helper_method, :parse_page_edit if base.respond_to? :helper_method
  end

end
