const dir = "src/scss/lib";
const outputDir = "src/scss";

const fs = require('fs');

var settingsToImportString = "";
var filesToImportString = "";

var files = fs.readdirSync(dir);
files.forEach(file => {
    let newFileName = file;
    if (!fs.lstatSync(dir + "/" + file).isDirectory()) {

        if (!file.startsWith("_")) {
            newFileName = "_" + newFileName;
        }
        if (file.endsWith("settings.scss") || file.endsWith("Settings.scss")){
            settingsToImportString += '@import "lib/' + newFileName + '";\n';
        }
        else{
            filesToImportString += '@import "lib/' + newFileName + '";\n';
        }
        fs.readFile(dir + "/" + file, 'utf8',function (err, data) {
            if (err) {
                return console.log(err);
            }
            // console.log(data.match(/@import "\.\.\//g));
            var result = data.replace(/@import "\.\.\//g, '@import "../../');
            result = result.replace(/@import "[a-zA-z].*[\n\r]/g, "");
            result = result.replace(/@import '\.\.\//g, "@import '../../");
            result = result.replace(/@import '[a-zA-z].*[\n\r]/g, "");
            // var result = data;
            // console.log(result);

            fs.unlink(dir + "/" + file, function (err) {
                if (err) return console.log(err);
                fs.writeFile(dir + "/" + newFileName, result, 'utf8', function (err) {
                    if (err) return console.log(err);
                });
            });
        });
    }
});

fs.writeFile(outputDir + "/_defaultSettings.scss", settingsToImportString, err => {
    if (err) {
        throw err;
    }
});

// var newFileContent = settingsToImportString;
var newFileContent = '@import "settings";\n';
newFileContent += filesToImportString;

fs.writeFile(outputDir + "/_imports.scss", newFileContent, err => {
    if (err) {
        throw err;
    }
});