#! /usr/bin/env ruby

require 'time'


class Entry
  def initialize(fn)
    @input = fn
  end

  def title
    ensure_read
    @title
  end

  def date
    ensure_read
    @date
  end

  def categories
    ensure_read
    @categories
  end

  def body
    ensure_read
    @body
  end

  private

  def ensure_read
    data = File.read(@input)
    @title = @date = nil
    @categories = []
    @body = nil
    data.each_line.each_with_index do |line, line_no|
      line.chomp!
      if line.start_with?('Title: ')
        @title = line[7...-1]
      elsif line.start_with?('Date: ')
        @date = Time.parse(line[6...-1])
      elsif line.start_with?('Categories: ')
        @categories = line[12...-1].split(', ')
      elsif line == '' && @body.nil?
        @body = []
      elsif @body.nil?
        $stderr.outs "bad line #{line_no}: #{line}"
      else
        @body.push(line)
      end
    end
  end
end


class Printer
  class Entry
    attr_reader :entry, :fn

    def initialize(entry, fn)
      @entry, @fn = entry, fn
    end
  end


  def initialize(template)
    @template = template
    @categories = Hash.new
    
  end

  def parse(input_fn, output_fn)
    entry = ::Entry.new(input_fn)
    data = @template
    data.gsub!('__WOCLEMA_ENTRY__', entry.body.join("\n"))
    File.open(output_fn, 'w'){|fptr| fptr.puts data}

    fse = Entry.new(entry, output_fn)
    entry.categories.each do |cat|
      @categories[cat] ||= []
      @categories[cat] << fse
    end
  end

  def create_indices
    @categories.each do |cat, entries|
      puts cat
      entries.each{|e| puts "  #{e.entry.title} / #{e.entry.date}"}
    end
  end

  def category_fn(cat)
    cat.downcase.gsub(' ', '_')
  end
end

pr = Printer.new(File.read('template.html'))
pr.parse('raw/001', '_001')
pr.parse('raw/002', '_002')
pr.create_indices
