const path = require(`path`);
const fs = require(`fs`);

const log = console;

const createDirectories = (fullPath) => {
    try {
        const pathData = path.parse(fullPath);
        const directoriesArray = pathData.dir.split(path.sep);
        let start = '';
        let exists = '';
        let created = '';

        if (process.platform === `linux`) {
            start = '/';
        } else if (process.platform === 'win32') {
            start = pathData.root;

            directoriesArray.shift();
        }

        if (!pathData.ext) {
            directoriesArray.push(pathData.name);
        }

        directoriesArray.reduce((prevPath, dirName, index) => {
            const currentPath = path.join(prevPath, dirName);

            if (!fs.existsSync(currentPath)) {
                fs.mkdirSync(currentPath);

                created += path.sep + dirName;
            } else {
                exists = currentPath;
            }

            return currentPath;
        }, start);

        log.info(`add directories ${created} in ${exists}`);
    } catch (e) {
        log.error(`Error: createDirectories()\n`, e);
    }
};

module.exports = createDirectories;
