const path = require('path');
const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsProject = ts.createProject('tsconfig.json');
const clean = require('gulp-clean');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const less = require('gulp-less');
const bump = require('gulp-bump');

const LessPluginAutoPrefix = require('less-plugin-autoprefix');
const NpmImportPlugin = require('less-plugin-npm-import');
const merge2 = require('merge2');
const through2 = require('through2');

const babelConfig = {
  presets: [['@babel/preset-env'], '@babel/preset-react', '@babel/preset-typescript'],
  plugins: [
    '@babel/plugin-proposal-class-properties',
    ['@babel/plugin-transform-runtime', {helpers: false}],
  ],
};

const imgSource = [
  './src/**/imgs/**',
]
const tsdFiles = [
  './src/typings.d.ts',
];
const tsFiles = [
  './src/**/*.ts',
  './src/**/*.tsx',
  '!./src/**/demo/*.tsx'
];
const cssFiles = [
  './src/**/*.less'
];

const libDir = path.join(process.cwd(), 'lib');

gulp.task('clean', function () {
  return gulp.src(libDir, {allowEmpty: true}).pipe(clean());
});


gulp.task('ts', function () {
  const tsResult = gulp.src(tsFiles).pipe(tsProject());
  const dts = tsResult.dts.pipe(gulp.dest(libDir));
  const tsFilesStream = babelify(tsResult.js);
  return merge2([tsFilesStream, dts]);
});

gulp.task('image', function() {
  return gulp.src(imgSource).pipe(gulp.dest(libDir));
});
gulp.task('tsd', function() {
  return gulp.src(tsdFiles).pipe(gulp.dest(libDir));
});


function babelify(js) {
  let stream = js
      .pipe(sourcemaps.init())
      .pipe(babel(babelConfig))
      .pipe(
          through2.obj(function(file, encoding, next) {
              this.push(file.clone());
              if (file.path.match(/(\/|\\)style(\/|\\)index\.js/)) {
                    const content = file.contents.toString(encoding);
                    file.contents = Buffer.from(
                        content
                            .replace(/\/style\/?'/g, "/style/css'")
                            .replace(/\/style\/?"/g, '/style/css"')
                            .replace(/\.less/g, '.css'),
                    );
                    file.path = file.path.replace(/index\.js/, 'css.js');
                  this.push(file);
              }
              next();
          }),
      )
      .pipe(sourcemaps.write('.'));

  return stream.pipe(gulp.dest(libDir));
}

gulp.task('less', function() {
  const lessStream = gulp.src(cssFiles);

  const copyLess = lessStream
      .pipe(
          through2.obj(function(file, encoding, next) {
              this.push(file.clone());
              next();
          }),
      )
      .pipe(gulp.dest(libDir));
  const lessToCss = lessStream
      .pipe(
          less({
              javascriptEnabled: true,
              plugins: [
                  new NpmImportPlugin({ prefix: '~' }),
                  new LessPluginAutoPrefix({ browsers: ['last 2 versions', 'IE 9'] }),
              ],
              modifyVars: {
                  'root-entry-name': 'default',
              },
          }),
      )
      .pipe(gulp.dest(libDir));

  return merge2([copyLess, lessToCss]);
});

gulp.task('compile', gulp.series(['clean' ,'image', 'less', 'ts', 'tsd']));
// gulp.task('compile', gulp.series(['clean',  'image','ts']));
gulp.task('bump', function() {
  return gulp
      .src('./package.json')
      .pipe(bump({ type: process.argv.slice(3)[0].replace(/-/g, '') }))
      .pipe(gulp.dest('./'));
});

