# The "Model" is composed of simple data holders derived from whatever data source we 
# choose to use (currently the filesystem).  These data holders are wrapped by
# TemplateContent instances in the publishing module.  The exception is Template,
# which is used directly by the publishing module.

#------------------------------------------------
# EntryData - data representing a weblog entry.
#------------------------------------------------
class EntryData 
  include Comparable

  attr_reader :id, :title, :text, :date, :category, :baseUrl

  def initialize(id, title, text, date, category, baseUrl)
    @id, @title, @text, @date, @category, @baseUrl = id, title, text, date, category, baseUrl
  end

  def <=>(other)
    date <=> other.date
  end

end


#----------------------------------------------------
# CategoryData - data representing a category
#----------------------------------------------------
class CategoryData

  attr_reader :fileName, :numEntries

  def initialize(fileName, numEntries)
    @fileName, @numEntries = fileName, numEntries
  end

  def displayName
    @fileName.gsub("_"," ")
  end 

  def <=>(other)
    displayName <=> other.displayName
  end

end


#--------------------------------------------------------------
# Template - represents templates with replaceable parameters, 
# and provides the method by which the replacements are made.
#-------------------------------------------------
class Template
  def initialize(text)
    @text = text
  end

  def text
    @text
  end

  # Trickiest code in the entire system!  Apply "attribute" values 
  # from the passed Hash, to matching Template content variables 
  # (which have the form #{variable_name}), resulting in resolved content.  
  def apply(attribsHash)
    # Basically, the below finds each variable occurence, and the block supplies the
    # replacement value for that occurence from the attributes hash.  The outer gsub
    # ensures that all occurences of that variable are replaced.
    result = @text.gsub(/#\{\w+\}/){ |m|
               keywordRe = /#\{(\w+)\}/ # capture variable name in $1
               keywordRe.match(m)       # get the template symbol
               attribsHash[$1]          # yield return replacement for the symbol (variable_name) 
                                        # from hash, for use in gsub.
             }
    result
  end 

  def to_s
    @text
  end
end

