'use strict';

// MODULES IMPORT
const fs = require('fs');

// FUNCTIONS
function isDirectory(path) {
    return fs.statSync(distDir + path).isDirectory();
}

function addProjectPath(path) {
    return webBlogDirectory + path;
}

function removeByValue(array, value) {
    const index = array.indexOf(value);
    array.splice(index, 1);
    return array;
}

// gives a list of files and directories in the folder
function getWebBlogPaths() {
    const _webBlogPaths = fs.readdirSync(distDir);
    const ignorePaths = ['.npmignore'];
    ignorePaths.forEach((value)=> {
        removeByValue(_webBlogPaths, value);
    });
    return _webBlogPaths;
}

// VARIABLES
const webBlogDirectory = '../../';
const distDir = './dist/';
const _webBlogPaths = getWebBlogPaths();

const webBlogFiles = _webBlogPaths.filter((path)=> !isDirectory(path));
const webBlogDirectories = _webBlogPaths.filter((path)=> isDirectory(path));

// EXPORTS
module.exports = function (grunt) {
    // GRUNT CONFIG
    grunt.initConfig({
        // copies web-blog files
        copy: {
            "web-blog": {
                files: (()=> {
                    let tasks = [];

                    // DIRECTORIES
                    webBlogDirectories.forEach((path)=> {
                        tasks.push({
                            expand: true,
                            cwd: distDir + path + '/',
                            src: '**',
                            dest: addProjectPath(path) + '/'
                        })
                    });

                    // FILES
                    webBlogFiles.forEach((path)=> {
                        tasks.push({
                            src: distDir + path,
                            dest: webBlogDirectory + path
                        })
                    });

                    // .gitignore is not published as part of NPM module
                    tasks.push({
                        src: distDir + '.npmignore',
                        dest: webBlogDirectory + '.gitignore'
                    });

                    return tasks;
                })()
            }
        }
    });

    // loads Grunt plugins
    require('jit-grunt')(grunt);

    // GRUNT TASKS
    grunt.registerTask("init", [
        "copy:web-blog"
    ]);
};
