'use strict';

const path = require('path');
const utils = require('../utils');


const writeSprite = (srcPath, files, destPath, outputFile) => {
  const SVGSpriter = require('svg-sprite');

  const spriter = new SVGSpriter({
    destPath,
    svg: { dimensionAttributes: true },
    mode: {
      symbol: {
        dest: '',
        sprite: outputFile,
      },
    },
  });

  files.forEach((file) => {
    const filePath = path.resolve(srcPath, file);
    spriter.add(
      filePath,
      file,
      utils.getFileContent(filePath),
    );
  });

  spriter.compile((error, result) => {
    Object.keys(result).forEach((mode) => {
      Object.keys(result[mode]).forEach((resource) => {
        utils.writeFileContent(
          path.join(destPath, outputFile),
          result[mode][resource].contents
        );
      });
    });
  });
};


module.exports.generateSprite = () => {
  let srcPath, spriteFile;

  Promise.resolve()
    .then(() => {
      const args = utils.getArgs();

      if (!args.inFolder) {
        throw new Error('inFolder argument not provided');
      }

      srcPath = path.join(process.cwd(), args.inFolder);
      spriteFile = args.outFile;

      if (!args.outFile) {
        throw new Error('outFile not provided as argument');
      } else {
        if (args.outFile.indexOf('.svg') < 0) {
          throw new Error('outFile filename should be in svg file format');
        }
      }

      spriteFile = args.outFile;

      utils.logInfo(`Building svg sprite from : ${srcPath}`);
      utils.logInfo(`Generating sprite file output : ${spriteFile}`);

      return utils.getFilesGlob(srcPath, '**/*.svg');
    })

    .then((svgFiles) => {
      if (svgFiles.length === 0) {
        throw new Error('NO_FILES_FOUND');
      }

      utils.logInfo(`...found ${svgFiles.length} svg files`);

      return generateSvgsSprite(srcPath, path.join(srcPath, 'sprites'), spriteFile);
    })

    .catch((e) => {
      throw e;
    })
}


const generateSvgsSprite = module.exports.generateSvgsSprite = (svgsInPath, svgsSpritePath, svgsSpriteFile) => {
  const imagemin = require('imagemin');
  const imageminSvgo = require('imagemin-svgo');

  const svgsOutPath = path.join(svgsInPath, 'temp');

  let svgFiles;

  return Promise.resolve()
    .then(() => {
      return utils.remove(svgsOutPath);
    })
    .then(() => {
      return utils.remove(path.join(svgsSpritePath, svgsSpriteFile));
    })
    .then(() => {
      return utils.getFilesGlob(svgsInPath, '**/*.svg');
    })
    .then((files) => {
      svgFiles = files;

      utils.logInfo('Optimizing svg files');
      utils.logInfo('Found :');
      console.log(svgFiles);

      const filesPaths = svgFiles.map(f => path.join(svgsInPath, f));

      return imagemin(filesPaths, {
        glob: false,
        destination: svgsOutPath,
        plugins: [
          imageminSvgo({
            plugins: [
              { name: 'cleanupIDs', remove: false },
              { name: 'cleanupNumericValues', floatPrecision: 2 },
              { name: 'removeStyleElement', remove: true },
              { name: 'removeTitle', remove: true },
            ],
            multipass: true
          })
        ]
      })
    })

    .then((files) => {
      utils.logSuccess(`${files.length} processed`);

      utils.logInfo('Creating svg sprite');


      writeSprite(svgsOutPath, svgFiles, svgsSpritePath, svgsSpriteFile);

      // generating json output list
      const outList = svgFiles.map((f) => {
        return f.substr(0, f.indexOf('.svg'));
      });

      const svgsSpriteFileJson = svgsSpriteFile.substr(0, svgsSpriteFile.indexOf('.svg')) + '.json';
      console.log(svgsSpriteFileJson);

      utils.writeJsonFileSync(path.join(svgsSpritePath, svgsSpriteFileJson), outList);

      utils.logSuccess(`OK => ${svgsSpritePath} generated`);
    })

    .then(() => {
      return utils.remove(svgsOutPath);
    })

    .then(() => {
      utils.logSuccess(`${svgsOutPath} cleaned up`);
    })

    .catch((e) => {
      throw e;
    })
}
