module ParserLayout
  require 'radius'
  include ParserCommon

  def parse_layout_contents(layout)
    content = layout.content.force_encoding('UTF-8')
    context = parser_layout_contents(layout)
    parser = Radius::Parser.new(context, :tag_prefix => 'r')
    parser.parse(content)
  end

  def parser_layout_contents(layout)
    Radius::Context.new do |c|
      c.define_tag 'javascripts' do |tag|
      end
      c.define_tag 'stylesheets' do |tag|
      end
      c.define_tag 'adbanner' do |tag|
      end
      c.define_tag 'menu' do |tag|
        layout.build_menu(:levels => 0, :values => {}) unless layout.menu
        layout.menu.levels = i = tag.attr['level'].to_i
        layout.menu.values.merge!({'home' => tag.attr['home']}) if i == 1
        layout.menu.values.merge!({"id_#{i}" => tag.attr['id'], "class_#{i}" => tag.attr['class'], "li_class_#{i}" => tag.attr['li_class'], "li_incremental_#{i}" => tag.attr['li_incremental']})
        layout.menu.save
        tag.expand
      end
      c.define_tag 'content' do |tag|
        layout.layout_parts.create(:name => tag.attr['name'], :editable => true)
      end
      c.define_tag 'image' do |tag|
        image = layout.design.images.detect{ |i| i.file_identifier.eql?(parse_html_image(tag.expand)) }
        image.update_attributes(:name => tag.attr['name'], :html_id => tag.attr['id'], :html_class => tag.attr['class'])
      end
    end
  end
  
  def parse_html_image(html)
    html.scan(/(?<=\<img)(.*?)(?=\/\>)/){
      $1.gsub(' ','').scan(/(?<=src=\")(.*?)(?=\")/){
        return File.basename($1).gsub(/[\\\"]/, '')
      }
    }
  end
end
