// Iconfont task
'use strict';

import { dest, src, series } from 'gulp';
import iconfont from 'gulp-iconfont';
import iconFontCSS from 'gulp-iconfont-css';
import { config } from '../config.mjs';
import Stream from 'stream';
import PluginError from 'plugin-error';
import consolidate from 'consolidate';
import path from 'path';
import Vinyl from 'vinyl';

const runTimestamp = Math.round(Date.now() / 1000);

const _iconsFont = () => {
  return src([config.iconfont.src], {'encoding': false})
    .pipe(iconFontCSS({
      fontName: config.iconfont.fontName,
      fontPath: '../fonts/' + config.iconfont.fontName + '/',
      path: config.iconfont.mixinsTemplate,
      targetPath: config.iconfont.mixinsDest,
    }))
    .pipe(iconfont({
      fontHeight: 1001,
      fontName: config.iconfont.fontName,
      formats: ['ttf', 'eot', 'woff', 'woff2'],
      normalize: true,
      prependUnicode: true,
      timestamp: runTimestamp,
    }))
    .pipe(dest(config.iconfont.dest, { encoding: false }));
};

const iconsJson = function() {
  return src([config.iconfont.src])
    .pipe(createIconJson({
      path: config.iconfont.jsonTemplate,
      fontName: config.iconfont.fontName,
      targetPath: config.iconfont.jsonDist,
    }))
    .pipe(dest('components/00-theme/00-base/09-icons'));
}

function createIconJson(config) {
  let glyphMap = [],
    outputFile,
    currentCodePoint;

  config = {
    aliases: {},
    firstGlyph: 0xE001,
    engine: 'lodash',
    cacheBuster: '',
    ...config,
  };

  // Define starting point.
  let currentGlyph = config.firstGlyph;

  const stream = Stream.PassThrough({
    objectMode: true
  });

  stream._transform = function(file, unused, cb) {
    let fileName;

    if (file.isNull()) {
      this.push(file);
      return cb();
    }

    // Create output file.
    if (!outputFile) {
      outputFile = new Vinyl({
        base: file.base,
        cwd: file.cwd,
        path: path.join(file.base, config.targetPath),
        contents: file.isBuffer() ? Buffer.alloc(0) : new Stream.PassThrough()
      });
    }

    fileName = path.basename(file.path, '.svg');
    currentCodePoint = (currentGlyph++).toString(16).toUpperCase();

    // Add glyph.
    glyphMap.push({
      fileName: fileName.split(`u${currentCodePoint}-`).pop(),
      codePoint: currentCodePoint
    });

    // Prepend codePoint to input file path for gulp-iconfont
    // inputFilePrefix = 'u' + currentCodePoint + '-';
    //
    // file.path = path.dirname(file.path) + '/' + inputFilePrefix + path.basename(file.path);

    //this.push(file);

    cb();
  }

  stream._flush = function(cb) {
    var content;
    if (glyphMap.length) {
      consolidate[config.engine](config.path, {
        glyphs: glyphMap,
      }, function(err, html) {
        if (err) {
          throw new PluginError('icons:font', 'Error in template: ' + err.message);
        }

        content = Buffer.from(html);

        if (outputFile.isBuffer()) {
          outputFile.contents = content;
        } else {
          outputFile.contents.write(content);
          outputFile.contents.end();
        }

       stream.push(outputFile);

        cb();
      });
    } else {
      cb();
    }
  };

  return stream;
}

export const iconsFont = series(_iconsFont, iconsJson);
