package org.matrix.testNg.web.report;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.matrix.exception.GlobalException;
import org.matrix.testNg.web.entity.DataBean;
import org.matrix.testNg.web.entity.DataBeans;
import org.matrix.testNg.web.entity.ReportMessage;
import org.matrix.util.ReporterUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author mruny
 */
public class GenerateReporter {

    private static final String OUTPUT_FOLDER = System.getProperty("user.dir") + "/htmls";
    private static final String FILE_NAME = UUID.randomUUID().toString().replace("-", "") + ".html";

    FileOutputStream out;
    Writer writer;

    public ReportMessage generateReport() {
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
            cfg.setClassForTemplateLoading(this.getClass(), "/templates");
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            Template temp = cfg.getTemplate("overview.ftl");
            Map context = new HashMap();
            ReporterData reporterData = new ReporterData();
            DataBean dataBean = reporterData.testDataBean();
            List<DataBeans> dataBeansList = reporterData.testDataBeans();
            // 这里是公共的信息.
            for (DataBeans bean : dataBeansList) {
                context.put("overView", dataBean);
                if (bean.getResult()) {
                    context.put("pass", dataBeansList);
                } else {
                    context.put("fail", dataBeansList);
                }
            }
            //文件夹不存在的话进行创建
            File reportDir = new File(OUTPUT_FOLDER);
            if (!reportDir.exists() && !reportDir.isDirectory()) {
                reportDir.mkdir();
            }
            // 输出流
            out = new FileOutputStream(OUTPUT_FOLDER + "/" + FILE_NAME);
            writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
            // 转换输出
            temp.process(context, writer);
            writer.flush();
            ReportMessage reportMessage = new ReportMessage();
            reportMessage.setUrl(FILE_NAME);
            return reportMessage;
        } catch (Exception e) {
            throw new GlobalException(e.getMessage());
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ReporterUtils.map = new HashMap<>();
        }
    }

}