/**
 * This task generates a .go template file with the content script.
 */

const fs = require('fs');
const console = require('console');
const config = require('./config');

console.info('Start generating the pages template');

function generateTemplate(fileName) {
    const content = fs.readFileSync(`${config.outputDir}/${fileName}`).toString();

    const lines = content.split('\n');

    let templateVariable = '';
    lines.forEach((line, idx) => {
        const escapedLine = line.replace(/("|\\)/g, '\\$1');
        // eslint-disable-next-line prefer-template
        templateVariable += '"' + escapedLine + '\\n"';
        if (idx < lines.length - 1) {
            templateVariable += ' +\n';
        }
    });

    return templateVariable;
}

const fileContents = `// Code generated by pages DO NOT EDIT.

package proxy

import "text/template"

const blockedPageTemplate = ${generateTemplate('blocked.html')}

var blockedPageTmpl = template.Must(template.New("blockedPage").Parse(blockedPageTemplate))
`;

fs.writeFileSync(config.goTemplatePath, fileContents);

console.info('Finished generating the pages template');
console.info(`The template file was written to ${config.goTemplatePath}`);
