package wf.doyle.blockbuster.file;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.CaseFormat;
import wf.doyle.blockbuster.App;
import wf.doyle.blockbuster.item.LibraryItem;
import wf.doyle.blockbuster.util.EnumLineType;
public class FileWriter {
protected static final long serialVersionUID = 0L;
private Path path;
private List<String> lines = new ArrayList<String>();
public String joinedString;
public FileWriter(Path path)
{
this.lines.add("// SERIAL " + serialVersionUID);
this.path = path;
}
public FileWriter serializeItems()
{
List<LibraryItem> items = App.items;
Collections.sort(items, new Comparator<LibraryItem>()
{
@Override
public int compare(LibraryItem arg0, LibraryItem arg1)
{
return arg0.getType().toString().compareTo(arg1.getType().toString());
}
});
EnumLineType header = null;
for(LibraryItem item : items)
{
if(header != item.getType())
{
this.lines.add("");
this.lines.add("[" + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, item.getType().toString()) + " data]");
this.lines.add("// data is " + StringUtils.join(FileReader.containing.get(item.getClass().getName()), ", ").trim());
header = item.getType();
}
this.lines.add(item.toString());
}
this.joinedString = StringUtils.join(this.lines, "\r\n");
return this;
}
public void save()
{
File file = this.path.toFile();
try
{
file.createNewFile();
}
catch(IOException e)
{
App.LOGGER.error("Could not create new file", e);
}
try(PrintWriter writer = new PrintWriter(file))
{
writer.write(this.joinedString);
}
catch(Exception e)
{
App.LOGGER.error("Could not write to file", e);
}
}
}