var fs = require('fs');
var path = require('path');

const SRC_PATH = './src/default/icons/svg/';
const DEST_PATH = './dist/default/icons/svg/';
const SPRITE_NAME = 'actions-sprite.svg';

var markup = fs.readFileSync(SRC_PATH + SPRITE_NAME).toString();
var lines = markup.split(/\n/g);
var symbols = {};
var currentSymbol = null;

if (!fs.existsSync(DEST_PATH)){
  fs.mkdirSync(DEST_PATH, {recursive: true});
}


lines.forEach(function(line){
    var open = line.match(/symbol.*?id="(.*?)"/);
    var close = line.match(/<\/symbol>/);
    if(currentSymbol){
        symbols[currentSymbol].push(line);
    }
    if(open){
        currentSymbol = open[1].replace("Icons=", "").toLowerCase();
        symbols[currentSymbol] = [line];
    }
    if(close){
        symbols[currentSymbol] = symbols[currentSymbol].join('\n').replace('<symbol', '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"').replace('</symbol', '</svg');
        fs.writeFileSync(path.join(DEST_PATH + currentSymbol + '.svg'), symbols[currentSymbol]);
        currentSymbol = null;
    }
});

fs.readdir(SRC_PATH, function(err, items) {
    if (err) {
      console.log(`cant read ${SRC_PATH} directory`);
    }

    const filesToCopy = items.filter((i) => i.toLowerCase().endsWith('.svg') && i.toLowerCase() != SPRITE_NAME);
    filesToCopy.forEach((file) => fs.copyFileSync(SRC_PATH + file, DEST_PATH + file.replace("Icons=", "").toLowerCase()));
});

console.log( Object.keys(symbols) );