'use strict';

// GLOBAL
const path = require('path');
const moment = require('moment');

// LOCAL
const tools = require('../../utils/tools');

// FETCH ARGS
const { dryRun } = tools.getArgs();


const storeBuildMetadataBackend = (pkg, pkgVersion, pkgMetadata, envTarget) => {
  return Promise.resolve()
    .then(() => {
      tools.logInfo('Storing package BUILD metadata...');

      let generatedMetadata = {};
      let versions = [];

      let pkgMetadataFile = path.join(pkg.paths.root, 'package-build-metadata.json');

      if (tools.isFileExists(pkgMetadataFile)) {
        generatedMetadata = require(pkgMetadataFile);
        versions = generatedMetadata.versions;
      }

      versions.push({ name: pkgVersion, envTarget: envTarget, gitMetadata: pkgMetadata });
      generatedMetadata.versions = versions;

      tools.logInfo(`Write metadata on ${pkgMetadataFile}`);
      if (dryRun) {
        tools.logInfo('DRY-RUN...');
        console.log(generatedMetadata);
      } else {
        tools.writeJsonFileSync(pkgMetadataFile, generatedMetadata);
      }
    })

    .catch((e) => {
      throw e;
    });
};

const storeMetadataVersionsBackend = (pkg, pkgVersion, duration, envTarget) => {
  return Promise.resolve()
    .then(() => {
      tools.logInfo('Storing package version history metadata...');

      let generatedMetadata = {};
      let versions = [];
      let pkgMetadataFile = path.join(pkg.paths.root, 'package-versions-metadata.json');

      if (tools.isFileExists(pkgMetadataFile)) {
        generatedMetadata = require(pkgMetadataFile);
        versions = generatedMetadata.versions;
      }

      const newVersionMetadata = {
        name: pkg.name,
        version: pkgVersion,
        date: moment(new Date()).format("YYYYMMDD-HH:mm"),
        npmPkg: pkg.npmPkg,
        duration: duration,
        envTarget: envTarget,
      };

      console.log(newVersionMetadata);
      versions.push(newVersionMetadata);
      generatedMetadata.versions = versions;

      tools.logInfo(`Write metadata on ${pkgMetadataFile}`);

      if (dryRun) {
        tools.logInfo('DRY RUN...outputing newVersionMetadata');
        console.log(newVersionMetadata);

      } else {
        tools.writeJsonFileSync(pkgMetadataFile, generatedMetadata);
      }
    })

    .catch((e) => {
      throw e;
    })
}

const storePipelineMetadata = (pkgMetadata) => {
  return Promise.resolve()
    .then(() => {
      tools.logInfo('Storing package pipeline metadata into root variables...');

      const variablesFile = path.join(process.cwd(), 'variables');

      let fileContent;
      if (tools.isFileExists(variablesFile)) {
        fileContent = tools.getFileContent(variablesFile);
      }

      if (pkgMetadata && pkgMetadata.issues) {
        const issuesList = pkgMetadata.issues.join(',');
        tools.logInfo(`Unique issues found for this version : ${issuesList}`);

        tools.logInfo(`Write metadata on ${variablesFile}`);
        if (!dryRun) {
          fileContent += `export ISSUES_LIST=${issuesList}\n`;
          tools.writeFileContent(variablesFile, fileContent);
        }
      } else {
        tools.logInfo('No issues found for this release');
      }
    })

    .catch((e) => {
      console.log(e);
    });
};


module.exports.storeMetadataBackend = (pkg, pkgVersion, pkgMetadata, isMaster, duration, envTarget) => {
  tools.logTitle('Storing Backend metadata...');

  return Promise.resolve()
    .then(() => {
      return storeMetadataVersionsBackend(pkg, pkgVersion, duration, envTarget);
    })

    .then(() => {
      if (isMaster) {
        return storeBuildMetadataBackend(pkg, pkgVersion, pkgMetadata, envTarget);
      }
    })

    .then(() => {
      if (isMaster) {
        return storePipelineMetadata(pkgMetadata);
      }
    })

    .then(() => {
      tools.logSuccess();
    })

    .catch((e) => {
      throw e;
    });
};

