'use strict';

// local requires
const Handlebars = require('handlebars');
const express = require('express');
const path = require('path');
// use this for checking if file exists because it's asynchronous:
const UtilFileSystem = require('../utils/UtilFileSystem');
const fileExists = UtilFileSystem.fileExists;
const mkdir = UtilFileSystem.mkdir;
const copyFile = UtilFileSystem.copyFile;
const writeFile = UtilFileSystem.writeFile;
const readFile = UtilFileSystem.readFile;

/*
set up the static server, for serving static files. This needs to serve the files under base path and the index.html needs to have
the base tag set with the basePath so the client app will automatically access URLs under the base path
 */
module.exports.setupStaticServer = async function(app) {
    logger.info("Setting up static file server...");

    // ensure private folder is present
    const privateFolderPath = path.join(__dirname, '../private');
    if (!await fileExists(privateFolderPath)) {
        logger.info('Creating private folder...');
        await mkdir(privateFolderPath);
    }

    const privateIndexHtmlPath = `${privateFolderPath}/index.html`;
    // ensure that we have private/index.html; copy client/index.html if not yet present
    if (!await fileExists(privateIndexHtmlPath)) {
        logger.info('Copying client/index.html to private folder...');
        const clientIndexHtmlPath = path.join(__dirname, '../../client/index.html');
        await copyFile(clientIndexHtmlPath, privateIndexHtmlPath);
        const noBuildMessage = `
            <h1 style="font-family: sans-serif; color:red;">Build Required</h1>
            <p  style="font-family: sans-serif;">
                This formbird server has no frontend installed. If you need to run the formbird frontend on this server,
                you can build it using the following steps:
                <ul>
                    <li>
                        <b>Backend/Integration Developer:</b> If you do not need to make frontend changes, please call 'gulp dist'
                        to ensure the necessary files are generated. This will provide the fastest possible frontend because a
                        production build will be performed.
                    </li>
                    <li>
                        <b>Frontend/Full-stack Developer:</b> If you're running the app for development via 'gulp dev' or
                        'npm start', please access the front-end on port <a href="http://localhost:4200">4200</a>,
                        so that the core app will reload when frontend changes are made.
                    </li>
                    <li>
                        <b>Production Server:</b> If this installation needs a frontend, speak to support to install the frontend
                        for production. If this installation is for the rest api only then the frontend may not be needed.
                    </li>
                </ul>
            </p>
        `;
        await UtilFileSystem.writeFile(privateIndexHtmlPath, noBuildMessage);
    }

    // read private/index.html
    logger.info("Reading index.html... Writing base tag using handlebars to server under base path...");
    const htmlData = await readFile(privateIndexHtmlPath);
    // copy private/index.html into the server/public folder, including the base tag in basePath.
    // Use handlebars to put the base path into the base tag
    const handlebarsSource = htmlData.toString();
    const hbTemplate = Handlebars.compile(handlebarsSource.toString());
    const BaseURLPath = require('./BaseURLPath');
    // the baseData will be passed into Handlebars, and the variables in the html templates with {{ }} will be replaced
    // with the values from baseData
    const templateData = {
        urlBasePath: BaseURLPath.basePathWithDomain
    };
    const parsedIndexHtml = hbTemplate(templateData);

    // ensure public folder is present
    const publicFolderPath = path.join(__dirname, '../public');
    if (!await fileExists(publicFolderPath)) {
        logger.info('Creating public folder...');
        await mkdir(publicFolderPath);
    }

    // write the result to the server/public folder
    await writeFile(`${publicFolderPath}/index.html`, parsedIndexHtml);
    logger.info('Saved index.html with base path to server/public');
    logger.info("Serving static files from base path: " + BaseURLPath.basePath);
    app.use(BaseURLPath.basePath, express.static(path.join(__dirname, '../public')));
};
