/*eslint-disable*/

var https = require('https');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');

var dest = 'src/core/skin/rc-font';
var icomoon = 'https://i.icomoon.io/public/6483cc0f53/SW/';

var files = {
    'style.scss': 'style.scss',
    'style.css': 'style.css',
    'variables.scss': 'variables.scss',
    'fonts/rc-font.eot': 'rc-font.eot',
    'fonts/rc-font.svg': 'rc-font.svg',
    'fonts/rc-font.ttf': 'rc-font.ttf',
    'fonts/rc-font.woff': 'rc-font.woff',
    'fonts/rc-font.woff2': 'rc-font.woff2',
};

var download = function(url, dest) {

    return new Promise(function(res, rej) {

        var file = fs.createWriteStream(dest);

        console.log('Downloading', dest);

        https.get(url, function(response) {

            response.pipe(file);

            file.on('finish', function() {
                file.close(function() {  // close() is async, call cb after close completes
                    console.log('Finished', dest);
                    res(file);
                });
            });

        }).on('error', function(err) {
            console.error('Error while downloading', dest, err.message);
            // fs.unlink(dest); // delete the file async. (But we don't check the result)
            rej(err);
        });

    });

};

function makeIconNamesList(cssFileName, jsonFileName) {
    console.log('Extracting list of icons to', jsonFileName);

    let list = [];

    let classNames = fs.readFileSync(cssFileName)
        .toString()
        .match(/\.rc-icon-[^\s:]+/g);

    if (classNames) {
        list = _.uniq(classNames.map((className) => className.replace(/\.rc-icon-/, '')));
    }

    fs.writeFileSync(jsonFileName, JSON.stringify(list, undefined, 2));
}

Promise.all(Object.keys(files).map(function(file) {
    return download(icomoon + files[file], path.join(process.cwd(), dest, file));
})).then(function() {

    //rc-font

    var varsPath = path.join(process.cwd(), dest, 'variables.scss');

    fs.writeFileSync(
        varsPath,
        fs.readFileSync(varsPath)
            .toString()
            .replace('$icomoon-font-path: "." !default;', '$icomoon-font-path: "fonts" !default;')
    );

    var cssPath = path.join(process.cwd(), dest, 'style.css');

    fs.writeFileSync(
        cssPath,
        fs.readFileSync(cssPath)
            .toString()
            .split(icomoon + 'rc-font')
            .join('fonts/rc-font')
    );

    makeIconNamesList(cssPath, path.join(process.cwd(), dest, 'list.json'));

}).catch(function(e) {
    console.error(e);
    process.exit(1);
});