require('./global/index');
const fs = require('fs');
const ora = require('ora');
const chalk = require('chalk');
const webpack = require('webpack');
const path = require('path');
const qrcode = require('qrcode-terminal');
const zipDir = require('zip-directory');

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

const { _root, _src, _config } = require('./getBlConfig.js');
const ROOT = path.join(process.cwd(), _root);
const SRC = path.join(ROOT, _src);
const DIST = path.join(ROOT, _config, 'dist');

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

    if (
        stats &&
    stats.compilation &&
    stats.compilation.errors &&
    stats.compilation.errors.length > 0
    ) {
        process.stderr.write(
            'online-build-error:\n' +
        stats.toString({
            colors: true,
            modules: false,
            children: false,
            chunks: false,
            chunkModules: false,
        }) +
        '\n\n'
        );
    }

    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, 'production'), (err, stats) => {
        if (err) {
            throw err;
        }

        if (
            stats &&
      stats.compilation &&
      stats.compilation.errors &&
      stats.compilation.errors.length > 0
        ) {
            process.stderr.write(
                'online-build-error:\n' +
          stats.toString({
              colors: true,
              modules: false,
              children: false,
              chunks: false,
              chunkModules: false,
          }) +
          '\n\n'
            );
        }

        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';
        zipDir(DIST, path.join(ROOT, zipName), () => {
            if (!fs.existsSync(path.join(ROOT, 'zip'))) {
                fs.mkdirSync(path.join(ROOT, 'zip'));
            }
            fs.copyFile(zipName, path.join('zip', zipName), () => {
                const ip = getIpAddress();

                const sapprc = JSON.parse(
                    fs.readFileSync(path.join(ROOT, '.sapprc'), 'utf8')
                );
                const zipUrl = `https://miniapp.bilibili.com/applet/debug/${
                    sapprc.appId
                }_${sapprc.vAppId}?url=${encodeURIComponent(
                    `http://${ip}:3000/${zipName}`
                )}`;

                qrcode.generate(zipUrl);
                fs.unlink(path.join(ROOT, zipName), () => {});
                console.log(zipUrl);
                console.log(chalk.cyan('  Build service complete.\n'));
            });
        });
    });
});
