package org.matrix.testNg.report;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.matrix.exception.GlobalException;
import org.testng.*;
import org.testng.xml.XmlSuite;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    private static final LocalDateTime TIME = LocalDateTime.now();
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
    private static final String STRING = DATE_TIME_FORMATTER.format(TIME);
    private static final String OUTPUT_FOLDER = System.getProperty("user.dir") + "/";
    private static final String FILE_NAME = STRING + "-testNg.html";

    @Override
    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,
                               String outputDirectory) {
        try {
            //freemaker的配置
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
            cfg.setClassForTemplateLoading(this.getClass(), "/templates");
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            //freemaker的模板文件
            Template temp = cfg.getTemplate("overview.ftl");

            Map context = new HashMap();

            for (ISuite suite : suites) {
                Map<String, ISuiteResult> suiteResults = suite.getResults();
                for (ISuiteResult suiteResult : suiteResults.values()) {
                    ReporterData data = new ReporterData();
                    ITestContext testContext = suiteResult.getTestContext();
                    // 把数据填入上下文 测试结果汇总信息
                    context.put("overView", data.testContext(testContext));
                    //所有的测试方法
                    ITestNGMethod[] allTests = testContext.getAllTestMethods();
                    //未执行的测试方法
                    Collection<ITestNGMethod> excludeTests = testContext.getExcludedMethods();
                    IResultMap passedTests = testContext.getPassedTests();
                    //测试失败的测试方法
                    IResultMap failedTests = testContext.getFailedTests();
                    //测试跳过的测试方法
                    IResultMap skippedTests = testContext.getSkippedTests();

                    context.put("pass", data.testResults(passedTests, ITestResult.SUCCESS));
                    context.put("fail", data.testResults(failedTests, ITestResult.FAILURE));
                    context.put("skip", data.testResults(skippedTests, ITestResult.FAILURE));
                    context.put("allTest", allTests);
                    context.put("excludeTests", excludeTests);
                }
            }
            //文件夹不存在的话进行创建
            File reportDir = new File(OUTPUT_FOLDER);
            if (!reportDir.exists() && !reportDir.isDirectory()) {
                reportDir.mkdir();
            }
            // 输出流
            FileOutputStream out = new FileOutputStream(OUTPUT_FOLDER + "/" + FILE_NAME);
            Writer writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
            // 转换输出
            temp.process(context, writer);
            writer.flush();
        } catch (Exception e) {
            throw new GlobalException(e.getMessage());
        }
    }


}