const fs = require('fs');
const ora = require('ora');
const chalk = require('chalk');
const webpack = require('webpack');
const path = require('path');
const zipDir = require('zip-directory');

const renderConfig = require('./webpack.render');
const serviceConfig = require('./webpack.service');

const ROOT = process.cwd();
const SRC = path.join(ROOT, 'src');
const DIST = path.join(ROOT, 'dist');

if (!fs.existsSync(path.join(ROOT, 'zip'))) {
    fs.mkdirSync(path.join(ROOT, 'zip'));
}

const spinner = ora('building for pages...');
spinner.start();
webpack(renderConfig(ROOT), (err, stats) => {
    spinner.stop();
    if (err) {
        throw err;
    }

    process.stdout.write(stats.toString({
        colors: true,
        modules: false,
        children: false,
        chunks: false,
        chunkModules: false
    }) + '\n\n');

    console.log(chalk.cyan('  Build pages complete.\n'));

    webpack(serviceConfig(ROOT, SRC), (err, stats) => {
        if (err) {
            throw err;
        }

        process.stdout.write(stats.toString({
            colors: true,
            modules: false,
            children: false,
            chunks: false,
            chunkModules: false
        }) + '\n\n');

        fs.unlink(path.join(SRC, 'service.js'), () => {});

        const zipName = new Date().toJSON().replace(/[-:.TZ]/g, '') + '.zip';
        if (!fs.existsSync(path.join(ROOT, 'zip'))) {
            fs.mkdirSync(path.join(ROOT, 'zip'));
        }
        const zipPath = path.join(ROOT, 'zip', zipName);
        const latestZipPath = path.join(ROOT, 'zip', 'latest.zip');
        zipDir(DIST, zipPath, () => {
            fs.unlink(latestZipPath, () => {
                fs.copyFile(zipPath, latestZipPath, async() => {
                    console.log(chalk.cyan('  Build service complete.\n'));
                });
            });
        });
    });
});
