var cheerio = require('cheerio');
var extname = require('path').extname;
var _ = require('lodash');
var Prism = require('prismjs');
var he = require('he');

var jsonSyntax = require('./prism-json');

var isHTMLFile = function(filePath) {
  return /\.html|\.htm/.test(extname(filePath));
};

module.exports = function(options) {

  Prism.languages.json = options.json ? options.json : jsonSyntax;

  return function(files, metalsmith, done) {
    setImmediate(done);

    _.each(files, function(file) {

      // gulpsmith || vanilla Metalsmith support
      if(!isHTMLFile(file.path || name)) {
        return;
      }

      var contents = file.contents.toString();
      var $ = cheerio.load(contents);
      var highlighted = false;

      $('code').each(function() {

        var $this = $(this);
        var className = $this.attr('class');

        var targets = className ? className.split('language-') : ['', 'markup'];

        if(targets.length > 1) {
          highlighted = true;

          var language = targets[1];

          var html = (language === 'markup') ? $this.html() : he.decode($this.html());
          var highlightedCode = Prism.highlight(html, Prism.languages[language]);
          $this.html(highlightedCode);
        }
      });

      if(highlighted) {
        file.contents = new Buffer($.html());
      }

    });
  };

};
var cheerio = require('cheerio');
var extname = require('path').extname;
var _ = require('lodash');
var Prism = require('prismjs');
var he = require('he');

var jsonSyntax = require('./prism-json');

var isHTMLFile = function(filePath) {
  return /\.html|\.htm/.test(extname(filePath));
};

module.exports = function(options) {

  options = options || {};

  Prism.languages.json = options.json ? options.json : jsonSyntax;

  return function(files, metalsmith, done) {
    setImmediate(done);

    _.each(files, function(file, name) {

      // gulpsmith || vanilla Metalsmith support
      if(!isHTMLFile(file.path || name)) {
        return;
      }

      var contents = file.contents.toString();
      var $ = cheerio.load(contents);
      var highlighted = false;

      $('code').each(function() {

        var $this = $(this);
        var className = $this.attr('class');

        var targets = className ? className.split('language-') : ['', 'markup'];

        if(targets.length > 1) {
          highlighted = true;

          var language = targets[1];

          var html = (language === 'markup') ? $this.html() : he.decode($this.html());
          var highlightedCode = Prism.highlight(html, Prism.languages[language]);
          $this.html(highlightedCode);
        }
      });

      if(highlighted) {
        file.contents = new Buffer($.html());
      }

    });
  };

};

fix file path and default options