package com.twosigmaiq.magic.beanstalk.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

public class FileGenerator {

  private static Configuration initializeTemplateConfiguration() throws IOException {
    Configuration cfg = new Configuration(Configuration.getVersion());
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    return cfg;
  }

  /**
   * Generate a dockerrun.aws.json file with a custom user template
   * @param dockerrunFilePath the location of the dockerrun template
   * @param dockerrunOutputDestination the output directory
   * @param parameters a map to hydrate the template with
   * @throws IOException if failed to load the template file
   * @throws TemplateException if template generation fails
   */
  public static void generateUserDockerrunFile(
      String dockerrunFilePath,
      String dockerrunOutputDestination,
      Map<String, Object> parameters
  ) throws IOException, TemplateException {
    File templateFile = new File(dockerrunFilePath);
    Configuration cfg = initializeTemplateConfiguration();
    cfg.setDirectoryForTemplateLoading(templateFile.getParentFile());
    generateFileFromTemplate(cfg, templateFile.getName(), dockerrunOutputDestination, parameters);

  }

  /**
   *Generate a dockerrun.aws.json file with the default template
   * @param outputFilePath the output directory
   * @param parameters a map to hydrate the default template with
   * @throws IOException if failed to load the template file
   * @throws TemplateException if template generation fails
   */
  public static void generateDefaultDockerrunFile(
      String outputFilePath,
      Map<String, Object> parameters
  ) throws IOException, TemplateException {
    Configuration cfg = initializeTemplateConfiguration();
    cfg.setClassForTemplateLoading(FileGenerator.class, "/");
    final String defaultDockerrunTemplateFile = "DockerrunTemplate.ftlh";
    generateFileFromTemplate(cfg, defaultDockerrunTemplateFile, outputFilePath, parameters);
  }

  private static void generateFileFromTemplate(Configuration cfg,
      String templateFile,
      String outputFilePath,
      Map<String, Object> parameters) throws IOException, TemplateException {
    Template temp = cfg.getTemplate(templateFile);
    File file = new File(outputFilePath);
    if (file.getParent() != null) {
      file.getParentFile().mkdirs();
    }
    FileWriter writer = new FileWriter(file);
    temp.process(parameters, writer);
  }
}