"use strict";

//constants
var PUBLIC_FILES = "server/public/";
var COMPONENT_PUBLIC_FILES = PUBLIC_FILES + "vendor/custom-component-modules/";
var EXCLUDED_FILES = [COMPONENT_PUBLIC_FILES + '**/*.gz', COMPONENT_PUBLIC_FILES + '**/*.zip'];
var COMPONENT_DOC_LOADER_LINK = "api/loadComponentDoc";

//libs
var glob = require('glob');
var async = require('async');

//local libs
var UtilDocumentId = require('../../shared/utils/UtilDocumentId');
var SharedConstants = require('../../shared/constants/SharedConstants');
var SearchService = require('../search/SearchService');
var UtilType = require('../../shared/utils/UtilType');
const componentService = require('../database/dataServices/ComponentService');

//global vars
var clientResourceVersion = null;

function listResources(cb){
    var options = {
        nodir: true,
        ignore: EXCLUDED_FILES
    };

    glob(COMPONENT_PUBLIC_FILES + '**', options, function(err, files){
        // remove server/public from the path because this is not included in the url the browser calls to cache the file
        async.map(files, (file, callback) => {
            callback(null, file.replace(PUBLIC_FILES, ''));
        }, (err, resources) => {
            cb(null, resources);
        });
    });
}

function listComponentResources(userId, cb){

    componentService.getListComponentResources(userId).then(searchSucc, searchFail);

    function searchSucc(components) {
        let userComponents = [];

        async.each(components, function(component, callback) {
            const componentName = component.name;

            if (isValidComponentName(componentName)) {
                userComponents.push(COMPONENT_DOC_LOADER_LINK + "/" + componentName);
            } else {
                logger.error("Not caching component with invalid name: " + componentName);
            }

            callback();
        });

        cb(null, userComponents);
    }

    function searchFail(err) {
        logger.error("Failed retrieving component list from elastic. Error: " + err);
    }

}

function isValidComponentName(componentName) {
    if (!UtilType.hasValue(componentName)) return false;
    if (!UtilType.isString(componentName)) return false;
    if (componentName.indexOf(" ") !== -1) return false;
    if (componentName === 'undefined' || componentName === 'null') return false;

    return true;
}

function getClientResourceVersion(){

    if(!clientResourceVersion){
        clientResourceVersion = UtilDocumentId.generateId();
    }

    return clientResourceVersion;
}

exports.getClientResources = function(req, res){

    var resources;

    listResources(resourcesListed);

    function resourcesListed(err, list){

        resources = list;

        if(req.user && req.user.documentId){
            var userId = req.user.documentId;
            listComponentResources(userId, componentsListed);
        }else{
            componentsListed(null, []);
        }

    }

    function componentsListed(err, componentResources){
        res.json({resources : resources, componentResources: componentResources, version: getClientResourceVersion()});
    }

};