package se.bjurr.gitchangelog.internal.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public final class ResourceLoader {
  private ResourceLoader() {}

  public static String getResourceOrFile(final String resourceName) {

    String templateString = null;
    try {
      final Path templatePath = Paths.get(resourceName);
      if (templatePath.toFile().exists()) {

        Files.readAllBytes(templatePath);
      } else {
        InputStream inputStream =
            getResourceFromClassLoader(resourceName, ResourceLoader.class.getClassLoader());
        if (inputStream == null) {
          inputStream =
              getResourceFromClassLoader(
                  resourceName, Thread.currentThread().getContextClassLoader());
        }

        if (inputStream == null) {
          throw new FileNotFoundException(
              "Was unable to find file, or resouce, \"" + resourceName + "\"");
        }
        templateString =
            new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));
      }
    } catch (final IOException e) {
      throw new RuntimeException(resourceName, e);
    }
    return templateString;
  }

  private static InputStream getResourceFromClassLoader(
      final String resourceName, final ClassLoader classLoader) {
    InputStream inputStream = classLoader.getResourceAsStream(resourceName);
    if (inputStream == null) {
      inputStream = classLoader.getResourceAsStream("/" + resourceName);
    }
    return inputStream;
  }
}

@@ -493,25 +493,24 @@
 urceName) %7B%0A
-%0A
     String t
@@ -642,25 +642,24 @@
 ts()) %7B%0A
-%0A
         
 Files.re
@@ -650,16 +650,44 @@
         
+templateString = new String(
 Files.re
@@ -710,16 +710,41 @@
 atePath)
+, StandardCharsets.UTF_8)
 ;%0A      

read template from file