/**
 * AI Design Elements Build
 * @requires gulp, gulp sass, gulp sourcemaps
 * @author Asiainfo UXT Team
 */
/* plugins */
const gulp = require('gulp')
const sass = require('gulp-sass')
const clean = require('gulp-clean')
const rename = require('gulp-rename')
const autoprefixer = require('gulp-autoprefixer')
const sourcemaps = require('gulp-sourcemaps')
const cssnano = require('gulp-cssnano')
const iconfont = require('gulp-iconfont')
const consolidate = require('gulp-consolidate')
const fs = require('fs')
const path = require('path')
const htmlmin = require('gulp-htmlmin')
const gutil = require('gulp-util')
const concat = require('gulp-concat')
const runSequence = require('run-sequence')
const webserver = require('gulp-webserver')

const sassAidSrc = ['src/aid/aid.scss']/*, 'src/aid-only.scss', 'src/aid-animate-only.scss', 'src/aid-cmc.scss', 'src/aid-cuc.scss', 'src/aid-ctc.scss' */
const distPath = 'dist/'

const sassAidMobileSrc = ['src/aid-mobile/aid-mobile.scss']
const distMobilePath = 'dist-mobile/'

const iconOpts = {
  fontSrc: 'src/icons/',
  mobileFontSrc:  'src/icons-mobile/',
  timestamp: Math.round(Date.now() / 1000),
  template: 'aidesign-style',
  className: 'aid',
  fontName: 'AI Design Icons',
  fontPath: '../fonts/',
  fontFileName: 'aidesignicons-regular',
  iconVersion: '1.1.5'
}

const remixIconOpts = {
  fontSrc: 'src/icon-remix/',
  timestamp: Math.round(Date.now() / 1000),
  template: 'aidesign-style',
  className: 'remix',
  fontName: 'Remix Icons',
  fontPath: '../fonts/',
  fontFileName: 'remixicons-regular',
  iconVersion: '1.1.1'
}

const iconFontDist = 'src/icons/aid-icons-v' + iconOpts.iconVersion
const iconFontMobileDist = 'src/icons-mobile/aid-icons-v' + iconOpts.iconVersion
const iconFontRemixDist = 'src/icon-remix/remix-icon-v' + remixIconOpts.iconVersion

/**
 * desktop and mobile common task
 */
gulp.task('aid-icon-fonts', () => {
  gulp.src(['src/icons/svg-rename/*.svg'])
    .pipe(iconfont({
      fontName: iconOpts.fontName,
      fileName: iconOpts.fontFileName,

      formats: ['ttf', 'eot', 'woff', 'woff2', 'svg'],
      normalize: true,
      fontHeight: 1001,
      timestamp: iconOpts.timestamp
    }))
    .on('glyphs', (glyphs) => {
      const options = {
        className: iconOpts.className,
        fontFileName: iconOpts.fontFileName,
        fontName: iconOpts.fontName,
        fontPath: iconOpts.fontPath,
        glyphs: glyphs.map(mapGlyphs),
        version: iconOpts.iconVersion
      }
      gulp.src(iconOpts.fontSrc + `templates/${iconOpts.template}.css`)
        .pipe(consolidate('lodash', options))
        .pipe(rename({basename: iconOpts.fontFileName}))
        .pipe(gulp.dest(iconFontDist + '/css/'))
        .pipe(rename({extname: '.scss'}))
        .pipe(gulp.dest(iconFontDist + '/scss/'))
      // if you don't need sample.html, remove next 4 lines
      gulp.src(iconOpts.fontSrc + `templates/${iconOpts.template}.html`)
        .pipe(consolidate('lodash', options))
        .pipe(rename({basename: iconOpts.fontFileName}))
        .pipe(htmlmin({
          collapseWhitespace: true,
          minifyJS: true,
          minifyCSS: true,
          sortAttributes: true,
          sortClassName: true
        }))
        .pipe(gulp.dest(iconFontDist)) // set path to export your sample HTML
    })
    .pipe(gulp.dest(iconFontDist + '/fonts'))
})

 // mobile
gulp.task('aid-icon-fonts-mobile', () => {
    gulp.src(['src/icons-mobile/svg-rename/*.svg'])
    .pipe(iconfont({
      fontName: iconOpts.fontName,
      fileName: iconOpts.fontFileName,

      formats: ['eot', 'svg', 'woff', 'woff2', 'ttf'],
      normalize: true,
      fontHeight: 1001,
      timestamp: iconOpts.timestamp
    }))
    .on('glyphs', (glyphs) => {
      const options = {
        className: iconOpts.className,
        fontFileName: iconOpts.fontFileName,
        fontName: iconOpts.fontName,
        fontPath: '#{$icon-font-path}/',
        glyphs: glyphs.map(mapGlyphs),
        version: iconOpts.iconVersion
      }
      gulp.src(iconOpts.mobileFontSrc + `templates/${iconOpts.template}.css`)
        .pipe(consolidate('lodash', options))
        .pipe(rename({basename: iconOpts.fontFileName}))
        .pipe(gulp.dest(iconFontMobileDist + '/css/'))
        .pipe(rename({extname: '.scss'}))
        .pipe(gulp.dest(iconFontMobileDist + '/scss/'))
      // if you don't need sample.html, remove next 4 lines
      gulp.src(iconOpts.mobileFontSrc + `templates/${iconOpts.template}.html`)
        .pipe(consolidate('lodash', options))
        .pipe(rename({basename: iconOpts.fontFileName}))
        .pipe(htmlmin({
          collapseWhitespace: true,
          minifyJS: true,
          minifyCSS: true,
          sortAttributes: true,
          sortClassName: true
        }))
        .pipe(gulp.dest(iconFontMobileDist)) // set path to export your sample HTML
    })
    .pipe(gulp.dest(iconFontMobileDist + '/fonts'))
})

// remix
gulp.task('remix-icon-fonts', () => {
  gulp.src(['src/icon-remix/svg-rename/*/*.svg'])
  .pipe(iconfont({
    fontName: remixIconOpts.fontName,
    fileName: remixIconOpts.fontFileName,

    formats: ['eot', 'svg', 'woff', 'woff2', 'ttf'],
    normalize: true,
    fontHeight: 1001,
    timestamp: remixIconOpts.timestamp
  }))
  .on('glyphs', (glyphs) => {
    const options = {
      className: remixIconOpts.className,
      fontFileName: remixIconOpts.fontFileName,
      fontName: remixIconOpts.fontName,
      fontPath: remixIconOpts.fontPath,
      glyphs: glyphs.map(mapGlyphs),
      version: remixIconOpts.iconVersion
    }
    gulp.src(remixIconOpts.fontSrc + `templates/${remixIconOpts.template}.css`)
      .pipe(consolidate('lodash', options))
      .pipe(rename({basename: remixIconOpts.fontFileName}))
      .pipe(gulp.dest(iconFontRemixDist + '/css/'))
      .pipe(rename({extname: '.scss'}))
      .pipe(gulp.dest(iconFontRemixDist + '/scss/'))
    // if you don't need sample.html, remove next 4 lines
    gulp.src(remixIconOpts.fontSrc + `templates/${remixIconOpts.template}.html`)
      .pipe(consolidate('lodash', options))
      .pipe(rename({basename: remixIconOpts.fontFileName}))
      .pipe(htmlmin({
        collapseWhitespace: true,
        minifyJS: true,
        minifyCSS: true,
        sortAttributes: true,
        sortClassName: true
      }))
      .pipe(gulp.dest(iconFontRemixDist)) // set path to export your sample HTML
  })
  .pipe(gulp.dest(iconFontRemixDist + '/fonts'))
})

gulp.task('aid-cp-fonts', () => {
  gulp.src([iconFontDist + '/fonts/**/*', 'src/fonts/aid-notosans/*.{ttf,woff,eot,svg,woff2,otf}'])
    .pipe(gulp.dest(distPath + 'fonts'))
})

gulp.task('dist-clean', () => {
  gulp.src([distPath])
    .pipe(clean({force: true}))
})

/**
 * rename svg file with unicode
 */
gulp.task('set-unicode', () => {
  var codepoints = readCodepointsFromFile('src/icons/tmpl/codepoints-test')
  var codepointsmobile = readCodepointsFromFile('src/icons-mobile/tmpl/codepoints-test')
  gulp.src('src/icons/svg/*.svg')
    .pipe(rename(function (path) {
      path.basename = ('u' + codepoints[path.basename].toString(16) + '-' + path.basename)
    })).pipe(gulp.dest('src/icons/svg-rename'))
  gulp.src('src/icons-mobile/svg/*.svg')
  .pipe(rename(function (path) {
    path.basename = ('u' + codepointsmobile[path.basename].toString(16) + '-' + path.basename)
  })).pipe(gulp.dest('src/icons-mobile/svg-rename'))  
})

/**
 * rename svg file with unicode
 */
gulp.task('set-remix-unicode', () => {
  var codepoints = readCodepointsFromFile('src/icon-remix/tmpl/codepoints')
  gulp.src('src/icon-remix/svg/*/*.svg')
  .pipe(rename(function (path) {
    path.basename = ('u' + codepoints[path.basename].toString(16) + '-' + path.basename)
  })).pipe(gulp.dest('src/icon-remix/svg-rename'))
})

/**
 * 合并set-unicode和aid-icon-fonts 依赖执行任务
*/
gulp.task('resolve-icon', () => {
  runSequence('set-unicode', 'aid-icon-fonts')
})

// mobile
gulp.task('resolve-mobile-icon', () => {
  runSequence('set-unicode', 'aid-icon-fonts-mobile')
})

// remix
gulp.task('resolve-remix-icon', () => {
  runSequence('set-remix-unicode', 'remix-icon-fonts')
})

/**
 * This is needed for mapping glyphs and codepoints.
 */
function mapGlyphs (glyph) {
  return {name: glyph.name, codepoint: glyph.unicode[0].charCodeAt(0)}
}

/**
 * Gets the codepoints from the set filepath
 */
function readCodepointsFromFile (path) {
  var buffer = fs.readFileSync(path)
  return JSON.parse(buffer.toString())
}

/**
 * desktop task
 */
gulp.task('aid-sass', () => {
  gulp.src(sassAidSrc)
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(cssnano({
      discardComments: {removeAll: true},
      autoprefixer: true,
      zindex: false,
      reduceIdents: {keyframes: false},
      discardUnused: {keyframes: false}
    }))
    .pipe(autoprefixer({
      browsers: ['last 2 versions', '> 5%']
    }))
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('maps'))
    .pipe(gulp.dest(distPath + 'css/'))
})

// desktop default task
gulp.task('aid-desktop', function () {
  runSequence('aid-sass', 'aid-cp-fonts')
})

/**
 * mobile task
 */
gulp.task('aid-sass-mobile', () => {
  gulp.src(sassAidMobileSrc)
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(cssnano({
      discardComments: {removeAll: true},
      autoprefixer: true,
      zindex: false,
      reduceIdents: {keyframes: false},
      discardUnused: {keyframes: false}
    }))
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('maps'))
    .pipe(gulp.dest(distMobilePath + 'css/'))
})

// mobile default task
gulp.task('aid-mobile', function () {
  runSequence('aid-sass-mobile', 'aid-cp-fonts')
})

/**
 * gulp server
 */

gulp.task('server-desktop', function () {
  gulp.src('./').pipe(webserver({
    livereload: true,
    directoryListing: true,
    port: 8001,
    open: 'http://localhost:8001/doc/components-preview.html'
  }))
})

gulp.task('server-mobile', function () {
  gulp.src('./').pipe(webserver({
    livereload: true,
    directoryListing: true,
    port: 8002,
    open: 'http://localhost:8002/doc-mobile/mobile-components-preview.html'
  }))
})

gulp.task('watch-mobile', function () {
  gulp.watch('./src/**/*.scss', ['aid-mobile'])
})

gulp.task('watch-desktop', function () {
  gulp.watch('./src/**/*.scss', ['aid-desktop'])
})

gulp.task('open-server-mobile', function () {
  runSequence('server-mobile', 'watch-mobile')
})

gulp.task('open-server-desktop', function () {
  runSequence('server-desktop', 'watch-desktop')
})
