"use strict";
var fs = require('fs'),
    path = require('path');

const jsExtension = 'js';

var logic = {
    initDir: '',
    filesArray: [],
    skipPaths: [],
    /**
     * Goes through the directory and seeks for files with 'js' extension
     * @param startDirectory {String}
     * @param skipFiles {Array}
     * @returns {Object}
     */
    start: function (startDirectory, skipFiles) {
        var skipPaths = [];
        skipFiles.forEach(function(skipFile){
            skipPaths.push(new RegExp(skipFile));
        });
        this.skipPaths = skipPaths;
        if(!path.isAbsolute(startDirectory)){
            startDirectory = path.resolve(startDirectory);
        }
        this.initDir = startDirectory;
        this.filesArray = [];
        if(fs.statSync(startDirectory).isDirectory()){
            this.goThrough(startDirectory);
        } else {
            if(path.extname(startDirectory) === '.' + jsExtension) {
                this.filesArray.push(startDirectory);
            }
        }
        return this.filesArray;
    },
    /**
     * Recursively go through folder
     *
     * @param  directory {String}
     */
    goThrough: function (directory) {
        var files = fs.readdirSync(directory);
        for (var i = 0; i < files.length; i++) {
            var fileName = path.resolve(directory, files[i]);
            //exclude 'ext'-folder
            if(this.ignorePath(fileName)){
                continue;
            }
            if (fs.statSync(fileName).isDirectory()) {
                this.goThrough(fileName);
            } else {
                if(path.extname(fileName) === '.' + jsExtension) {
                    this.filesArray.push(fileName);
                }
            }
        }
    },

    /**
     * Detects if path fits to the skipPaths
     *
     * @param fileName {String}
     * @returns {boolean}
     */
    ignorePath: function (fileName){
        for(var k = 0; k < this.skipPaths.length; k++) {
            if (fileName.replace(new RegExp(path.sep.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"),'g'),'/').match(this.skipPaths[k])) {
                return true;
            }
        }
        return false;
    }
};
module.exports = {
    /**
     *
     * @param startDirectory {String}
     * @param skipFiles {Array} contains Strings which will be converted to RegExp's
     * @returns {Object}
     */
    start: function(startDirectory, skipFiles){
        return logic.start(startDirectory, skipFiles);
    }
};