package pl.tomaszdziurko.jvm_bloggers.mailing;


import com.google.common.base.Joiner;
import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.antlr.stringtemplate.StringTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPost;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class BlogSummaryMailGenerator {

    private Resource blogsSummaryTemplate;

    @Autowired
    public BlogSummaryMailGenerator(@Value("classpath:/mail_templates/blog_summary.st") Resource blogsSummaryTemplate) {
        this.blogsSummaryTemplate = blogsSummaryTemplate;
    }

    public String generateSummaryMail(List<BlogPost> posts, int numberOfDaysBackInThePast) {
        try {
            List<String> lines = Files.readLines(blogsSummaryTemplate.getFile(), Charset.forName("UTF-8"));
            String templateContent = Joiner.on("\n").join(lines);
            StringTemplate template = new StringTemplate(templateContent);
            template.setAttribute("days", numberOfDaysBackInThePast);
            template.setAttribute("newPosts", posts.stream().map(BlogPostForMailItem::new).collect(Collectors.toList()));
            return template.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}

@@ -84,43 +84,8 @@
 er;%0A
-import com.google.common.io.Files;%0A
 impo
@@ -444,16 +444,47 @@
 gPost;%0A%0A
+import java.io.BufferedReader;%0A
 import j
@@ -519,27 +519,28 @@
 ava.
-n
 io.
-charset.Charset
+InputStreamReader
 ;%0Aim
@@ -769,17 +769,16 @@
 asspath:
-/
 mail_tem
@@ -1023,44 +1023,80 @@
     
-List%3CString%3E lines = Files.readLines
+BufferedReader bufferedReader = new BufferedReader(new InputStreamReader
 (blo
@@ -1120,32 +1120,23 @@
 .get
-File(), Charset.forName(
+InputStream(), 
 %22UTF
@@ -1178,16 +1178,17 @@
 ontent =
+ 
  Joiner.
@@ -1205,13 +1205,59 @@
 oin(
-lines
+bufferedReader.lines().collect(Collectors.toList())
 );%0A 
@@ -1656,11 +1656,10 @@
 %0A    %7D%0A%0A
-%0A
 %7D%0A

Fix issue with loading template file from classpath inside of fat-jar