package com.capgemini.framework.deployment;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;

/**
 * Property ready for user inputs.
 **/
class DeployProperties {
  private static final Logger log = LoggerFactory.getLogger(DeployProperties.class);
  private final Properties propFile;

  DeployProperties(String aFilePath) {
    propFile = new Properties();
    try (FileInputStream theFileStream = getInputStream(aFilePath)) {
      propFile.load(theFileStream);
      displayValues();
    }
    catch (FileNotFoundException e) {
      log.error("The file has not been found: " + aFilePath, e);
    }
    catch (IOException e) {
      log.error("Error while reading file: " + aFilePath, e);
    }

  }

  /**
   * Display property file content for debug purpose.
   */
  private void displayValues() {
    if (log.isDebugEnabled()) {
      StringBuilder thePropValues = new StringBuilder();
      thePropValues.append("Property values:\n");

      for (Entry<Object, Object> currentProp : propFile.entrySet()) {
        String currentKey = currentProp.getKey().toString();
        String currentValue = currentProp.getValue().toString();
        thePropValues.append("\t").append(currentKey).append("=").append(currentValue).append("\n");
      }

      log.debug(thePropValues.toString());
    }
  }

  /**
   * Read input properties file.
   */
  private FileInputStream getInputStream(String aFilePath) throws FileNotFoundException {
    return new FileInputStream(new File(aFilePath));
  }

  /**
   * Retrieve a property value.
   *
   * @param aDynamicRef Reference of the the searched property
   * @return Property value
   */
  String getString(String aDynamicRef) {
    String thePropValue = "";
    if (propFile.containsKey(aDynamicRef)) {
      thePropValue = propFile.getProperty(aDynamicRef);
    }
    else {
      log.debug("Unknown property reference: {}", aDynamicRef);
    }
    return thePropValue;
  }
}
