package loc.statistics;

import loc.FilterSerializer;
import loc.IFilterSerializer;
import loc.filter.*;

import java.util.*;

public class StatisticsSerializer implements IStatisticsSerializer {
	public static char space              = ' ';
	public static String separator        = " - ";
	public static String lineBreak        = "\n";
	public static char underlineCharacter = '-';
//	public static int underlineLength     = 10;
	private Statistics statistics;
	private SortedSet<Map.Entry<Filter, FileStatistics>> sortedStatistics;
	private FilterSerializer filterSerializer = new FilterSerializer();
	private StringBuffer buffer;
	private List<String> filterStrings;
	private List<FileStatistics> fileStatistics;

	public StatisticsSerializer(Statistics statistics) {
		this.statistics = statistics;
		sortedStatistics = new TreeSet<>(new StatisticsComparator());
		sortedStatistics.addAll(statistics.getFilterFileStatisticsMap().entrySet());
	}

	@Override
	public String serialize() throws Exception {
		buffer = new StringBuffer();
		filterStrings = new ArrayList<>();
		fileStatistics = new ArrayList<>();
		int maxFilterStringLength = 0;
		for (Map.Entry<Filter, FileStatistics> entry: sortedStatistics) {
			String filterString = filterSerializer.serialize(entry.getKey());
			filterStrings.add(filterString);
			fileStatistics.add(entry.getValue());
			maxFilterStringLength = Math.max(maxFilterStringLength, filterString.length());
		}
		appendSerialized(maxFilterStringLength);
		return buffer.toString();
	}

	private void appendSerialized(int maxFilterStringLength) {
		buffer.append("Total - ");
		buffer.append(statistics.getTotalLines());
		buffer.append(" lines in ");
		buffer.append(statistics.totalFiles());
		buffer.append(" files");
		buffer.append('\n');
		append(underlineCharacter, maxFilterStringLength);
		buffer.append('\n');
		for (int i = 0; i < filterStrings.size(); i++) {
			String filterString = filterStrings.get(i);
			buffer.append(filterString);
			append(space, maxFilterStringLength - filterString.length());
			buffer.append(separator);
			append(fileStatistics.get(i));
			buffer.append(lineBreak);
		}
	}

	private void append(char c, int amount) {
		for (int i = 0; i < amount; i++) {
			buffer.append(c);
		}
	}

	private void append(FileStatistics fileStatistics) {
		buffer.append(fileStatistics.lineCount);
		buffer.append(" \tlines in ");
		buffer.append(fileStatistics.fileCount);
		buffer.append(" \tfiles");
	}
}

@@ -41,44 +41,24 @@
 erSe
-rializer;%0Aimport loc.IFilterSerializ
+quenceStringBuff
 er;%0A
@@ -511,77 +511,8 @@
 cs;%0A
-%09private FilterSerializer filterSerializer = new FilterSerializer();%0A
 %09pri
@@ -1114,24 +1114,59 @@
 atistics) %7B%0A
+%09%09%09Filter filter = entry.getKey();%0A
 %09%09%09String fi
@@ -1184,16 +1184,20 @@
 = filter
+.get
 Serializ
@@ -1198,16 +1198,18 @@
 rializer
+()
 .seriali
@@ -1211,30 +1211,22 @@
 rialize(
-entry.getKey()
+filter
 );%0A%09%09%09fi

Fix serialization Refactor