package site.kason.tempera.loader;

import site.kason.tempera.source.StringTemplateSource;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Nullable;
import kamons.stream.InputStreamUtil;
import site.kason.tempera.engine.TemplateLoader;
import site.kason.tempera.engine.TemplateNotFoundException;
import site.kason.tempera.engine.TemplateSource;

/**
 *
 * @author Kason Yang
 */
public class ClasspathTemplateLoader implements TemplateLoader {

  private final String[] suffixs;
  
  private String path = "/";

  public ClasspathTemplateLoader() {
    this(null);
  }

  public ClasspathTemplateLoader(@Nullable String[] suffixs) {
    if (suffixs == null || suffixs.length == 0) {
      suffixs = new String[]{""};
    }
    this.suffixs = suffixs;
  }

  public String getPath() {
    return path;
  }

  /**
   * Specify the path to search templates
   * @param path the path
   */
  public void setPath(String path) {
    path = path.replace('.', '/');
    if(!path.startsWith("/")){
      path = "/" + path;
    }
    if(!path.endsWith("/")){
      path += "/";
    }
    this.path = path;
  }

  @Override
  public TemplateSource load(String templateName) throws TemplateNotFoundException {
    templateName = templateName.replace('.', '/');
    if(templateName.startsWith("/")){
      templateName = templateName.substring(1);
    }
    for (String s : suffixs) {
      String fullName = path + templateName.replace('.', '/') + s;
      InputStream is = ClasspathTemplateLoader.class.getResourceAsStream(fullName);
      if (is != null) {
        try {
          String content = InputStreamUtil.readAsString(is, "utf-8");
          return new StringTemplateSource(templateName, content);
        } catch (IOException ex) {
          throw new TemplateNotFoundException(ex);
        }
      }
    }
    throw new TemplateNotFoundException(templateName);
  }

}

@@ -507,16 +507,56 @@
 ixs;%0A  %0A
+  private String encoding = %22utf-8%22;%0A  %0A
   privat
@@ -576,16 +576,16 @@
  = %22/%22;%0A
-
 %0A  publi
@@ -1166,16 +1166,154 @@
 h;%0A  %7D%0A%0A
+  public String getEncoding() %7B%0A    return encoding;%0A  %7D%0A%0A  public void setEncoding(String encoding) %7B%0A    this.encoding = encoding;%0A  %7D%0A%0A
   @Overr
@@ -1824,23 +1824,24 @@
 ing(is, 
-%22utf-8%22
+encoding
 );%0A     

allow custom encoding