package com.brilliance.isc.tool.compareviewpage;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

public class FileCompare {

    // 交易码
    public static String trans_code;

    // 生成文件名称
    public static String file_name;

    public void compareFile(File leftFile, File rightFile) {
        try(FileReader leftFileReader = new FileReader(leftFile);
            FileReader rightFileReader = new FileReader(rightFile);) {
            String leftText = IOUtils.toString(leftFileReader);
            String rightText = IOUtils.toString(rightFileReader);
            CompareResult compareResult = compareText(leftText, rightText);
            outputResult(compareResult);
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    public CompareResult compareText(String leftText, String rightText) {
        diff_match_patch dmp = new diff_match_patch();
        CompareResult compareResult = new CompareResult();
        LinkedList<diff_match_patch.Diff> diffs = dmp.diff_main(leftText,rightText);
        dmp.diff_cleanupSemantic(diffs);
        AtomicInteger counter = new AtomicInteger();
        diffs.forEach(diff -> {
            if(!diff.operation.equals(diff_match_patch.Operation.EQUAL)){
                counter.incrementAndGet();
            }
        });
        //设置差异
        compareResult.setEditCount(counter.intValue());
        compareResult.setDiffs(diffs);
        String html = dmp.diff_prettyHtml(diffs)
                .replaceAll("&para;","")
                .replaceAll("&amp;nbsp;","&nbsp;");
        compareResult.setResultHtml(html);
        return compareResult;
    }

    public void outputResult(CompareResult compareResult) {
        // 输出结果文件 OK_TRANSCODE_XXXX.html
        String html = compareResult.getResultHtml();
        String filename = (compareResult.getEditCount() == 0 ? "OK_" : "NO_") + trans_code + "_" + file_name;
        File targetFile = new File(new File(SourceConfig.targetFolder, trans_code), filename + ".html");
        try(FileWriter fileWriter = new FileWriter(targetFile)) {
            IOUtils.write(html, fileWriter);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 加入到统计文件
        String result = trans_code + ".csv";
        File resultFile = new File(new File(SourceConfig.targetFolder), result);
        try(FileWriter fileWriter = new FileWriter(resultFile, true)) {
            String content = trans_code + "_" + file_name + "," + compareResult.getEditCount() + "\n";
            IOUtils.write(content, fileWriter);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
