"use strict";
var fs = require('fs');
var path = require('path');
var SystemJS = require('systemjs');
var reflect = require('reflect-metadata');

var path_to_ab_library;
var classMapping;
var dir;
var packagepath = 'shared';

/*
 *  Initializes the ab namespace
 * */

exports.init = init;

function init(path_to_lib_base,loader) {
    var promise = new Promise(function(resolve) {
        path_to_ab_library = path_to_lib_base+'/'+packagepath;
        dir = path_to_ab_library+'/';
        SystemJS.config({
            baseURL: dir,
            defaultJSExtensions: true,
            paths: { "*": "*.js" },
            // transpiler:'typescript'
        });
        if(path_to_ab_library.startsWith('http')) {
            initLibRemote().then(function () {
                logClassMap();
                resolve()
            })
        }else{
            console.log(dir);
            classMapping = parseClassTree(dir);
            console.log(classMapping);
            saveClassMapping();
            loadLibSytemJS().then(function () {
                //exports.base = new exports.Base();
                logClassMap();
                resolve()
            })
        }
    });
    return promise;
}

function loadLibSytemJS(){
    var promise = new Promise(function(resolve) {
        let ab = exports;
        let importPromiseArray = [];
        Object.keys(classMapping).forEach(function(k){
            importPromiseArray.push(System.import(classMapping[k]))
        });
        Promise.all(importPromiseArray).then(function(modules) {
            Object.keys(modules).forEach(function(k){
                var module = modules[k];
                Object.keys(module).forEach(function(kk){
                    ab[kk]=module[kk];
                });
            });
            resolve();
        });
    });
    return promise;
}

// fixme:
function initLibRemote(){
    var promise = new Promise(function(resolve) {
        console.log(path_to_ab_library+'/classMap');
        System.import(path_to_ab_library+'/classMap.').then(function(map){
            console.log(map);
            classMapping = map;
            loadLibSytemJS().then(function () {
                logClassMap();
                resolve()
            })
        });
    });
    return promise;
}

// function loadLib(){
//     _.each(classMapping,function(v,k){
//         console.log(dir + v);
//         if(k !== 'Browser'){
//             let ref = require(dir + '/' +v);
//             _.each(ref,function(v2,k2){
//                 exports[k2]=v2
//             });
//         }
//     });
// }

function parseClassTree(dir){
    let map = {};
    let files = fileList(dir);
    let classes = fileList(dir,'js').map((file) => file.split(path.sep).slice(-1)[0]);
    let i = 0;
    Object.keys(files).forEach(function(k){
        var file = files[k];
        if(file.substr(file.lastIndexOf('.') + 1) == 'js'  && file.match('/'+packagepath+'/') && !file.match('.spec.js') && !file.match('index.js')){
            map[classes[i].split('.js')[0]] = file.split(dir)[1].slice(1).slice(0, -3);
        }
        i++;
    });
    return map
}

function saveClassMapping() {
    console.log('fixme: saveClassMapping');
    var script = 'export const classMap = \n';
    // fs.writeFile(path_to_ab_library+'/classMap.ts', script + JSON.stringify(classMapping), function (err) {
    //     if (err)
    //         return console.log(err);
    // });
}

function fileList(dir) {
    return fs.readdirSync(dir).reduce(function(list, file) {
        var name = path.join(dir, file);
        var isDir = fs.statSync(name).isDirectory();
        return list.concat(isDir ? fileList(name) : [name]);
    }, []);
}

function logClassMap(){
    let ab = exports;
    if(!ab.Util) {
        console.error('ERROR: app-base-lib library not initialized');
    }else{
        console.log('------------');
        console.log('ab namespace');
        console.log('------------');
        Object.keys(ab).forEach(function(k){
            console.log('at.'+k);
        });
        // console.log(at);
        console.log('------------');
        console.log('');
    }
}


