# script for self-compiling the compiler
# Author: Alexander Tsepkov

path = require('path')
fs = require('fs')
rapydscript = require('../lib/rapydscript')

module.exports = def compile_self(base_path, src_path, lib_path, start_time):
    compiled = {}
    baselib = rapydscript.parse_baselib(src_path, True)
    options = {
        beautify: True,
        private_scope: False,
        omit_baselib: False,
        write_name: False,
#        filename: file,
        readfile: fs.readFileSync,
        basedir: src_path,
        dropDocstrings: True,
        auto_bind: False,
        libdir: path.join(src_path, 'lib'),
        baselib: baselib,
        strict_names: True
    }

    # generate baselib
    # parse the library
    src = fs.readFileSync(path.join(src_path, 'baselib.pyj'), "utf8")
    ast = rapydscript.parse(src, options)

    # manually activate each key
    for key in baselib:
        ast.baselib[key] += 1

    # dump the code
    output = rapydscript.output(ast, options)
    compiled.baselib = output.toString()

    # HACK: generate a fake library for importing inside the compiler which the compiler will
    # use so it doesn't need to require() anything
    fs.writeFileSync(path.join(src_path, '_baselib.pyj'), "BASELIB = '''" + src.replace(/\\/g, '\\\\') + "'''", "utf8")

    # logic to run on each file we're compiling
    def compile(file):
        filepath = path.join(src_path, file + '.pyj')
        options.filename = file + '.pyj'
        compiled[file] = rapydscript.compile(fs.readFileSync(filepath, "utf8"), options)

    # build the compiler itself and its modules
    for file in ['rapydscript', 'self', 'compile', 'test']:
        compile(file)

    # clean up
    fs.unlinkSync(path.join(src_path, '_baselib.pyj'))

    console.log('Compiling RapydScript succeeded (', (Date().getTime() - start_time)/1000, 'seconds ), writing output...')

    for filename in compiled:
        fs.writeFileSync(path.join(lib_path, filename + '.js'), compiled[filename], "utf8")

    # output 'rapydscript.js' wrapped in private scope as 'rapydscript_web.js' for safer use in browser
    #  + could be loaded as amd-module
    # it is nice to be able to make independent instance of the compiler in the browser environment
    # to get it just call rapydscript.factory()
    factory =  """
    function factory(){
        "use strict";
        <compiled_rapydscript>
        exports.factory = factory;
        return exports;
    };
    if ((typeof define == "function") && define.amd) define([], factory)
    else window.rapydscript = factory();
    """
    factory = factory.replace('<compiled_rapydscript>', compiled['rapydscript'])
    wrapped = '(function(){\n"use strict";\n' + factory  +   '\n})();'
    fs.writeFileSync(path.join(lib_path, 'rapydscript_web.js'), wrapped, "utf8")
