var File, _, frontMatter, gulpBridge, metalsmith, through, utf8;

_ = require("lodash");

metalsmith = require("metalsmith");

frontMatter = require("front-matter");

utf8 = require("is-utf8");

File = require("gulp-util").File;

through = require("through2");

module.exports = gulpBridge = function(func) {
  var files;
  files = {};
  return through.obj(function(vinyl, enc, done) {
    var attributes, body, filename, ref;
    if (vinyl.isStream()) {
      done(new Error("Streaming is not supported."));
      return;
    }
    if (vinyl.isNull()) {
      done();
      return;
    }
    filename = vinyl.relative.replace(/\\/g, "/");
    if (utf8(vinyl.contents)) {
      ref = frontMatter(vinyl.contents.toString()), attributes = ref.attributes, body = ref.body;
      files[filename] = attributes;
      files[filename].contents = new Buffer(body);
    } else {
      files[filename] = {
        contents: vinyl.contents
      };
    }
    done();
  }, function(done) {
    var metal;
    metal = metalsmith(__dirname);
    func(metal);
    metal.run(files, (function(_this) {
      return function(err, files) {
        if (err) {
          return done(err);
        } else {
          _.each(files, function(file, filename) {
            return _this.push(new File({
              path: filename,
              contents: file.contents
            }));
          });
          return done();
        }
      };
    })(this));
  });
};
