#! /usr/bin/env node

fs = require('fs');

const EXPORT_PATH = process.cwd() + "/CHANGELOG.md";
const BUILD_INFO_PATH = process.cwd() + "/src/build.ts";

function getInitContent() {
    return "" +
`OPENReport ChangeLog
====================
${getNextContent()}
`;
}

function getNextContent() {
    return "" +
`Next
------
- [...]

`;
}

function getVersion(str) {
    var expr = /(?:version:\s*")(.*?)(?:")/gm
    return str.match(expr)[0].split("\"")[1];
}

function insertStringAtPosition(str, position, strToInsert) {
    return [str.slice(0, position), strToInsert, str.slice(position)].join('');
}

if (!fs.existsSync(BUILD_INFO_PATH)) {
    console.error(`File ${BUILD_INFO_PATH} not found. Cannot create or update CHANGELOG.md.`);
    return;
}

try {
    if (!fs.existsSync(EXPORT_PATH)) {
        let content = getInitContent();
        fs.writeFile(EXPORT_PATH, content, function (err) {
            if (err) return console.log(err);
            console.log('*** File CHANGELOG.md initialized with content: \n', content);
        });
        return;
    }
} catch(err) {
    console.error(err);
    return;
}

let content = fs.readFileSync(EXPORT_PATH, {encoding: 'utf8'});
let buildInfoContent = fs.readFileSync(BUILD_INFO_PATH, {encoding: 'utf8'});

// console.info("Actual content: ", content);
if (!content)
    content = getInitContent();

var buildVersion = getVersion(buildInfoContent);

console.log("Exporting in: ", EXPORT_PATH);
var newContent = content.replace("Next", buildVersion);
newContent = insertStringAtPosition(newContent, newContent.indexOf(buildVersion), getNextContent());

console.log("Updating CHANGELOG.md: \n", newContent.substring(0, Math.min(newContent.length - 1, 200)) + "...");

fs.writeFile(EXPORT_PATH, newContent, function (err) {
  if (err) return console.log(err);
  console.log('File generated.');
});
