package com.chulung.ciki.processor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.chulung.craft.enumerate.CateLevelEnum;
import com.chulung.craft.mapper.CikiMapper;
import com.chulung.craft.model.BaseComponent;
import com.chulung.craft.model.Ciki;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import freemarker.template.Version;

@Component
public class TemplateProcessor extends BaseComponent {
	@Autowired
	private CikiMapper cikiMapper;
	private Configuration cfg = new Configuration(new Version("2.3.23"));

	public TemplateProcessor() throws IOException {
		cfg.setDirectoryForTemplateLoading(new File(getClass().getResource("/com/chulung/ciki/templates/").getPath()));
		cfg.setDefaultEncoding("UTF-8");
		cfg.setNumberFormat("#");
		new Thread(() -> {
			try {
				Thread.sleep(1000);
				this.processor();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}).start();
	}

	public void processor() throws Exception {
		logger.info("starting processor...");
		generateCiki(this.getCikisByParentId(1));
	}

	private void generateCiki(List<Ciki> cikis) throws Exception {
		String rootPath = System.getProperty("website.root");
		File file = new File(rootPath + "/ciki");
		FileUtils.deleteDirectory(file);
		file.mkdir();
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("cikis", cikis);
		printTemplate(hashMap, "indexPage.ftl", file.getPath() + "/index.html");
		cikis.forEach(c -> {
			File file2 = new File(file.getPath() + "/" + c.getEnIndex());
			file2.mkdir();
			c.getCikis().forEach(a -> {
				if (a.getCateLevel() == CateLevelEnum.ITEM) {
					try {
						HashMap<String, Object> hashMap2 = new HashMap<>();
						hashMap2.put("cateIndex", c.getEnIndex());
						hashMap2.put("cate", c.getTitle());
						hashMap2.put("ciki", a);
						hashMap2.put("html", a.getHtml());
						printTemplate(hashMap2, "contextPage.ftl", file2.getPath() + "/" + a.getEnIndex() + ".html");
					} catch (Exception e) {
						this.errorLog(e);
					}
				}
			});
		});

	}

	private void printTemplate(Map<String, Object> data, String templateName, String outputPath)
			throws IOException,
			TemplateException {
		Template template = cfg.getTemplate(templateName);
		Writer out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8");
		template.process(data, out);
		out.flush();
		out.close();
	}

	private List<Ciki> getCikisByParentId(Integer parentId) {
		Ciki record = new Ciki();
		record.setParentId(parentId);
		List<Ciki> categories = this.cikiMapper.select(record);
		categories.forEach(c -> c.setCikis(this.getCikisByParentId(c.getId())));
		return categories;
	}

}

@@ -365,16 +365,75 @@
 eUtils;%0A
+import org.springframework.beans.factory.InitializingBean;%0A
 import o
@@ -1093,18 +1093,45 @@
 mponent 
+implements InitializingBean
 %7B%0A
-
 %09@Autowi
@@ -1242,385 +1242,8 @@
 );%0A%0A
-%09public TemplateProcessor() throws IOException %7B%0A%09%09cfg.setDirectoryForTemplateLoading(new File(getClass().getResource(%22/com/chulung/ciki/templates/%22).getPath()));%0A%09%09cfg.setDefaultEncoding(%22UTF-8%22);%0A%09%09cfg.setNumberFormat(%22#%22);%0A%09%09new Thread(() -%3E %7B%0A%09%09%09try %7B%0A%09%09%09%09Thread.sleep(1000);%0A%09%09%09%09this.processor();%0A%09%09%09%7D catch (Exception e) %7B%0A%09%09%09%09e.printStackTrace();%0A%09%09%09%7D%0A%09%09%7D).start();%0A%09%7D%0A%0A
 %09pub
@@ -1282,16 +1282,16 @@
 ption %7B%0A
-
 %09%09logger
@@ -1306,16 +1306,21 @@
 tarting 
+ciki 
 processo
@@ -2969,10 +2969,467 @@
 es;%0A%09%7D%0A%0A
+    @Override%0A    public void afterPropertiesSet() throws Exception %7B%0A        cfg.setDirectoryForTemplateLoading(new File(getClass().getResource(%22/com/chulung/ciki/templates/%22).getPath()));%0A        cfg.setDefaultEncoding(%22UTF-8%22);%0A        cfg.setNumberFormat(%22#%22);%0A        new Thread(() -%3E %7B%0A            try %7B%0A                this.processor();%0A            %7D catch (Exception e) %7B%0A                e.printStackTrace();%0A            %7D%0A        %7D).start();%0A    %7D%0A
 %7D%0A

fix ciki 静态化bug