'use strict';

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

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

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



module.exports.getMetadata = (project) => {
  const DEVOPS_METADATA_PATH = configUtils.global.getConfigOptions().DEVOPS_METADATA_PATH;

  return Promise.resolve()
    .then(() => {
      if (!DEVOPS_METADATA_PATH) {
        throw new Error(`Devops metadata folder ${DEVOPS_METADATA_PATH} NOT FOUND`) ;
      }

      return tools.getJsonFileContent(path.join(DEVOPS_METADATA_PATH,  project.devopsVersionsMetadataFile));
    })
    .catch((e) => {
      throw e;
    })
}



module.exports.storeMetadata = (project, newVersion, envTarget) => {
  const appReleaseDate = moment(new Date()).format("DD/MM/YYYY HH:mm");
  const DEVOPS_METADATA_PATH = configUtils.global.getConfigOptions().DEVOPS_METADATA_PATH;

  return Promise.resolve()
    .then(() => {
      tools.logTitle('Storing application versions metadata...');

      const metadataFile = path.join(DEVOPS_METADATA_PATH, project.devopsVersionsMetadataFile);

      let generatedMetadata;
      let versions;

      if (tools.isFileExists(metadataFile)) {
        generatedMetadata = require(metadataFile);
        versions = generatedMetadata.versions;
      } else {
        generatedMetadata = {};
        versions = [];
      }

      versions.push({
        version: newVersion,
        releaseDate: appReleaseDate,
        envTarget: envTarget
      });

      generatedMetadata.versions = versions;

      if (!dryRun) {
        tools.writeJsonFileSync(metadataFile, generatedMetadata);
      }
    })

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

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