'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();


const 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.devopsEnvsMetadataFile));
    })
    .catch((e) => {
      throw e;
    })
}



const storeMetadata = (project, newVersion, metadata, envTarget) => {
  const appReleaseDate = moment(new Date()).format("DD/MM/YYYY HH:mm");
  const appInfos = `${newVersion} - ${appReleaseDate}`;
  const DEVOPS_METADATA_PATH = configUtils.global.getConfigOptions().DEVOPS_METADATA_PATH;

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

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

      let generatedMetadata;

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

      generatedMetadata[envTarget] = {
        version: newVersion,
        releaseDate: appReleaseDate,
        infos: appInfos,
        dependencies: metadata
      };

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

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

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



module.exports = {
  getMetadata,
  storeMetadata,
}
