require 'i18n'

module Jekyll
  class Linter < Generator
    safe true

    def slugify(s)
      I18n.available_locales = [:pt_BR]
      I18n.locale = :pt_BR
      I18n.transliterate(s)
        .gsub(/[\W]+/, ' ')
        .strip
        .gsub(/\s\s+/, '-')
        .downcase
        .gsub(' ', '-')
        .gsub('_', '-')
    end

    def assert_field(document, field)
      f = document.data[field]
      raise "Undefined '#{field}' for #{document.path}" unless f
      f
    end

    def assert_frontmatter_fields(document)
      title = assert_field document, 'title'
      layout = assert_field document, 'layout'
      date = document.date.strftime('%Y-%m-%d') unless layout == 'page'
      slug = assert_field document, 'slug'

      if 'post' != layout
        raise "Layout mismatch: expected 'post', got '#{layout}' for #{document.path}"
      end

      unless layout == 'page' then
        path = "_posts/#{date}-#{slug}.md"
        unless path == document.relative_path then
          raise "date/filename mismatch:\ndate+slug: #{path}\nfilename:  #{document.relative_path}"
        end
      end

      if slugify(title) != slug then
        puts 'WARNING!'
        puts "Filename isn't a slug of the title for '#{document.path}':\nslug:  '#{slug}'\ntitle: '#{slugify(title)}'"
        puts "Fix with:\n  mv _posts/#{date}-#{slug}.md _posts/#{date}-#{slugify(title)}.md"
      end
    end

    def generate(site)
      site.collections['posts'].docs.each do |document|
        assert_frontmatter_fields(document)
      end
    end
  end
end
