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


var srcPath ='.'

/*****************************************
 * svg转iconfont 替代iconfont.com的方案
 *****************************************/
 function clean_iconfont(cb){
  return gulp.src(`${srcPath}/dist`,{read:false,allowEmpty:true})
  .pipe($.clean());
}
function iconfontLess(cb){
  var fontName = 'iconfont';
  return gulp.src(`${srcPath}/svg/*.svg`)
    .pipe($.iconfontCss({
      fontName: fontName,
      path: `${srcPath}/templates/_icons.less`,
      targetPath: 'iconfont.less',
      fontPath: '~@/assets/iconfont/'
    }))
    .pipe($.iconfont({
      fontName: fontName,
      formats: ['svg', 'ttf', 'eot', 'woff', 'woff2'],
      normalize: true
      }))
    .pipe(gulp.dest(`${srcPath}/dist/less/`));
}

function iconfontCss(cb){
  var fontName = 'iconfont';
  return gulp.src(`${srcPath}/svg/*.svg`)
    .pipe($.iconfontCss({
      fontName: fontName,
      path: `${srcPath}/templates/_icons.css`,
      targetPath: 'iconfont.css',
      fontPath: `${srcPath}/`
    }))
    .pipe($.iconfont({
      fontName: fontName,
      formats: ['svg', 'ttf', 'eot', 'woff', 'woff2'],
      normalize: true
      }))
    .pipe(gulp.dest(`${srcPath}/dist/css/`));
}


function iconfontExample(cb){

  var files = fs.readdirSync(`${srcPath}/svg/`); 

  let icons=[]
  files.forEach(function(file){
    console.log(file);
    if(/\.svg$/.test(file)){
      icons.push(file.replace(/\.\w+$/, ''))
    }
  });

  return gulp.src(`${srcPath}/templates/index.html`)
    .pipe($.template({icons: icons}))
    .pipe(gulp.dest(`${srcPath}/dist/css/`));
}


exports.iconfont = gulp.series(clean_iconfont,iconfontLess,iconfontCss,iconfontExample);
// exports.iconfontCss = gulp.series(clean_iconfont,iconfontCss,iconfontExample);

