/**
 * Remove old files, build frontend and copy files to dist and build backend and copy files to dist.
 */

import fs from 'fs-extra';
import Logger from 'jet-logger';
import childProcess from 'child_process';

// Setup logger
const logger = new Logger();
logger.timestamp = false;


(async () => {
    try {
        // Remove current build
        await remove('./dist/')

        // build frontend and copy the build files to dist folder in order to serve them from there
        await exec('npm run build', './../frontend/')
        await move('./../frontend/build', './dist/frontend-build')

        // Copy production env file
        await copy('./src/pre-start/env/production.env', './dist/pre-start/env/production.env')
        // Copy back-end files
        await exec('tsc --build tsconfig.prod.json', './')
    } catch (err) {
        logger.err(err)
    }
})()


function remove(loc: string): Promise<void> {
    return new Promise((res, rej) => {
        return fs.remove(loc, (err) => {
            return (!!err ? rej(err) : res())
        })
    })
}


function copy(src: string, dest: string): Promise<void> {
    return new Promise((res, rej) => {
        return fs.copy(src, dest, (err) => {
            return (!!err ? rej(err) : res())
        })
    })
}

function move(src: string, dest: string): Promise<void> {
    return new Promise((res, rej) => {
        return fs.move(src, dest, (err) => {
            return (!!err ? rej(err) : res())
        })
    })
}

function exec(cmd: string, loc: string): Promise<void> {
    return new Promise((res, rej) => {
        return childProcess.exec(cmd, {cwd: loc}, (err, stdout, stderr) => {
            if (!!stdout) {
                logger.info(stdout)
            }
            if (!!stderr) {
                logger.warn(stderr)
            }
            return (!!err ? rej(err) : res())
        })
    })
}
