module ParserLayout
  require 'nokogiri'

  def parse_body(layout)
    body = Nokogiri::HTML(layout.body)

    body.css('.page_content').each do |content|
      layout.layout_parts.build(:name => content['name'])
    end

    body.css('.page_image').each do |image|
      image = layout.design.images.detect{ |i| i.file_identifier.eql?(parse_html_image(image.to_html)) }
      image.update_attributes(:name => image['name'], :html_id => image['id'], :html_class => image['class']) if image
    end

    body.css('.page_menu').each do |menu|
      layout.build_menu(:levels => 0, :values => {}) unless layout.menu
      layout.menu.levels = i = menu['level'].to_i
      layout.menu.values.merge!({'home' => menu['home']}) if i == 1
      layout.menu.values.merge!({"id_#{i}" => menu['id'], "class_#{i}" => menu['class'], "li_class_#{i}" => menu['li_class'], "li_incremental_#{i}" => menu['li_incremental']})
    end
    
  end

  def parse_html_image(html)
    html.scan(/(?<=\<img)(.*?)(?=\/\>)/){
      $1.gsub(' ','').scan(/(?<=src=\")(.*?)(?=\")/){
        return File.basename($1).gsub(/[\\\"]/, '')
      }
    }
  end


end
