module Jekyll

  class ReadmePage < Page
    def initialize(site, base, dir, src, idx)
      @site = site
      @base = base
      @dir = dir
      @name = 'index.md'

      self.process(@name)
      self.data ||= {}
      
      content = File.read(src, **Utils.merged_file_read_opts(site, {})).each_line.to_a

      self.data['layout'] = 'page'
      self.data['title'] = content[0].match(/^#* ?(.*)\n$/)[1]
      slug = self.data['title'].match(/^([^:]*):.*$/)
      if slug
        self.data['slug'] = slug[1]
      end
      self.data['sort'] = idx
      self.content = content[1..content.size].join
    end
  end

  class ReadmePageGenerator < Generator
    safe true

    def generate(site)
      # Go through all READMEs, and add them as pages
      readmes = site.config['readmes']
      return if readmes.nil?
      base = readmes['src_base']
      dir = readmes['out_base']
      idx = 0
      for project in readmes['projects']
          site.pages << ReadmePage.new(site, site.source, File.join(dir, project['name']), File.join(base, project['src'] ? project['src'] : project['name'], 'README.md'), idx)
          idx += 1
      end
    end
  end

end
