package com.quant.comm;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

public class Template{
	private static String readTxtFile(String filePath){
		String lineTxt = "";
        try {
            String encoding="utf-8";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt2;
                while((lineTxt2 = bufferedReader.readLine()) != null){
                	lineTxt +=lineTxt2;
                }
                read.close();
	        }else{
	            System.out.println("找不到指定的文件");
	        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return lineTxt;
	}
	
	//严格按照提供的字符串替换，key为模板中的名字，用{}包起来的部分，value为替换的值
	private static String replaceTxt(String _template, List<HashMap<String, String>> _list) {
		String str = "";
		for (HashMap<String,String> map: _list) {
			String str2 = new String(_template);
			Set<Entry<String, String>> entrySet = map.entrySet();  
	        for (Entry<String, String> entry : entrySet) {  
	        	str2 = str2.replace("{"+entry.getKey()+"}", entry.getValue()==null?"":entry.getValue());
	        }  
	        str += str2;
		}
		return str;
	} 
	//srcFile模块，dstFile目标位置
	public static void createTemplate(String srcFile, String dstFile, List<HashMap<String, String>> _list) {
		String oldString = Template.readTxtFile(srcFile);
		String newString = Template.replaceTxt(oldString, _list);
		newString ="document.write(\""+ newString.replace("\"", "\\\"") +"\");";
		try {
			OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(dstFile),"UTF-8");
			fw.write(newString);
	        fw.flush();   
	        fw.close();
		} catch (IOException e) {
			System.out.println("写入文件失败" + dstFile);
		}  
         
	}
}