const handler = require('serve-handler');
const pkg = require('../package.json');
const { createProxyMiddleware } = require('http-proxy-middleware');
const chalk = require('chalk');
const boxen = require('boxen');

const port = pkg.serve.port; 

const http = require('http');
const snapshotProxyHandler = createProxyMiddleware(pkg.serve.proxy);


const server = http.createServer((req, res) => {
    return snapshotProxyHandler(req, res, () => {
        return handler(req, res, {
            public: process.cwd(),
            renderSingle: true,
            cleanUrls: false,
            headers: [{
                source: '/lib/MessageWorker.js',
                headers: [{
                    key: 'Service-Worker-Allowed',
                    value: '/'
                }]
            }]
        });
    });
});

server.listen(port, () => {
    console.log(`${chalk.yellow('WebViewer SDK Demo Server is listening at')} ${chalk.blue.bold(port)}`);
    const details = server.address();

    let localAddress;

    if(typeof details === 'string') {
        localAddress = details;
    } else if(typeof details === 'object' && details.port) {
        const address = details.address === '::' ? 'localhost' : details.address;
        localAddress = `http://${address}:${details.port}/`;
    }
    if(localAddress) {
        console.log(boxen(`
${chalk.bold('Basic WebViewer Address')}: ${chalk.cyan(localAddress+'examples/PDFViewCtrl/basic_webViewer/')}

${chalk.bold('Complete WebViewer Address')}: ${chalk.cyan(localAddress+'examples/UIExtension/complete_webViewer/')}
        `, {
            borderColor: 'green',
            borderStyle: 'bold',
            padding: 1,
            margin: 1
        }));
    }
})