import { resolve } from 'path'
import chalk from 'chalk'
import { src, dest } from 'gulp'
import gulpSass from 'gulp-sass'
import dartSass from 'sass'
import autoprefixer from 'gulp-autoprefixer'
import cleanCSS from 'gulp-clean-css'
import rename from 'gulp-rename'

const DIR_SRC = resolve(__dirname, '..', 'packages')
const DIR_COMP = resolve(__dirname, DIR_SRC, 'components')
const DIR_DIST = resolve(DIR_COMP, 'dist')

export default function build() {
  const sass = gulpSass(dartSass)

  return src(resolve(DIR_COMP, '**/style.scss'))
    .pipe(sass.sync())
    .pipe(autoprefixer({ cascade: false }))
    .pipe(
      cleanCSS({}, (details) => {
        console.log(
          `${chalk.cyan(details.name)}: ${chalk.yellow(details.stats.originalSize / 1000)} KB -> ${chalk.green(
            details.stats.minifiedSize / 1000
          )} KB`
        )
      })
    )
    .pipe(
      rename((path) => {
        if (path.dirname.startsWith('dg')) {
          const basename = path.dirname.slice(0, -4)
          path.dirname = ''
          path.basename = basename
        }
      })
    )
    .pipe(dest(DIR_DIST))
}
