'use strict';

(function () {

  var gulp = require('gulp');

  var $ = require('gulp-load-plugins')();
  var fs = require('fs');
  var chalk = require('chalk');

  var through = require('through-gulp');
  var imageminWebp = require('imagemin-webp');

  var path = require('../path.js');

  module.exports = function (pathname, options, callback) {

    var devDir = pathname.config && pathname.config.dev_dir ? pathname.config.dev_dir : '';
    var publishDir = pathname.config && pathname.config.publish_dir ? pathname.config.publish_dir : './';

    publishDir = options.outpath || publishDir;

    var _pathname = path.join(pathname.root, devDir || '', pathname.output);

    _pathname = $.util.replaceExtension(_pathname, '.png');

    if (!fs.existsSync(_pathname)) {
      _pathname = $.util.replaceExtension(_pathname, '.jpeg');
    }

    if (!fs.existsSync(_pathname)) {
      _pathname = $.util.replaceExtension(_pathname, '.jpg');
    }

    if (!fs.existsSync(_pathname)) {
      _pathname = $.util.replaceExtension(_pathname, '.gif');
    }

    console.log(chalk.yellow('src:') + ' ' + chalk.grey(_pathname));

    gulp.src(_pathname, {
      base: path.join(pathname.root, devDir || '')
    }).pipe($.plumber()).pipe(imageminWebp({
      quality: 50
    })()).on('error', $.util.log).pipe($.if(options.publish && pathname.config, gulp.dest(publishDir, {
      cwd: pathname.root
    }))).pipe(through(function (file) {
      callback(null, file.contents);
      return file;
    }));
  };
})();