package cn.edu.seu.ise.dca.util;

import java.util.ArrayList;
import java.util.List;

import difflib.Delta;
import difflib.DiffRow;
import difflib.DiffRow.Tag;
import difflib.DiffRowGenerator;
import difflib.DiffUtils;
import difflib.Patch;

public class FileComparator {
	private String original;
	private String revised;
	
	public FileComparator(String original, String revised) {
		this.original = original;
		this.revised = revised;
	}
	
	/**
	 * @return the patch between original file and revised file
	 */
	public Patch getPatch() {
		return DiffUtils.diff(FileUtil.fileToLines(original), FileUtil.fileToLines(revised));
	}
	
	/**
	 * @return the list of delta chunks between original file and revised file
	 */
	public List<Delta> getDelates() {
		return getPatch().getDeltas();
	}
	
	/**
	 * @return the list of delta lines between original file and revised file
	 */
	public List<DiffRow> getComparedLines() {
		Patch patch = DiffUtils.diff(FileUtil.fileToLines(original), FileUtil.fileToLines(revised));
		DiffRowGenerator generator = new DiffRowGenerator.Builder().ignoreBlankLines(true)
			.columnWidth(Integer.MAX_VALUE).build();
		return generator.generateDiffRows(FileUtil.fileToLines(original), FileUtil.fileToLines(revised), patch);
	}
	
	/**
	 * @return the list of delta lines that are not not equal
	 */
	public List<DiffRow> getChangedLines() {
		List<DiffRow> AllRows = getComparedLines();
		List<DiffRow> diffRows = new ArrayList<DiffRow>();
		for(DiffRow row : AllRows) {
			if(row.getTag() != Tag.EQUAL) 
				diffRows.add(row);
		}
		return diffRows;
	}	
	
	/**
	 * @return the number of deltas
	 */
	public long sizeOfChangedDeltas() {
		return getDelates().size();
	}
	
	/**
	 * @return the number of changed code lines
	 */
	public long sizeOfChangedLines() {
		return getChangedLines().size();
	}
	
	
}
