require 'xml/parser'

class Entry < ActiveRecord::Base
  validates_presence_of :updated
  acts_as_tree :order=>"updated"
  belongs_to :author

  # ensure valid XML
  validates_each :title, :summary, :content do |model, attr, value|
    @@xmlparser ||= XML::Parser.new
    begin
      @@xmlparser.parse "<div>#{value}</div>" if value
    rescue
      model.errors.add attr, 'is not well formed XML'
    ensure
      @@xmlparser.reset
    end
  end

  # muddle the model: construct uniform resource identifier by date
  def by_date
    base = (parent or self)
    {
     :action => 'by_date',
     :year => base.updated.year.to_s,
     :month => sprintf('%02d', base.updated.month),
     :day => sprintf('%02d', base.updated.day),
     :path => [base.slug],
     :anchor =>  ('x'+$1 if atomid =~ /tag:.*:\d+-(\d+)/)
    }
  end

  # muddle the model: construct uniform resource identifier by id
  def by_id
    {
     :action => 'by_id',
     :path =>  [($1 if atomid =~ /tag:.*:(\d+)/)],
     :anchor =>  ($1 if atomid =~ /tag:.*:\d+-(\d+)/)
    }
  end
end
