package org.cmdline.sudoku;

import net.n3.nanoxml.*;
import java.awt.Color;
import java.io.*;
import java.util.*;

public class PuzzleExport implements Runnable {

	Vector cells = null;
	Stack solution = null;
	File exportFile = null;
	boolean generated = false;
	
	public PuzzleExport(Vector cells,Stack solution,File exportFile,boolean generated) {
		this.cells = cells;
		this.solution = solution;
		this.exportFile = exportFile;
		this.generated = generated;
	}
	
	public void run() {
		try {
			// Need to read in current contents of export file if any
			// initialize required if none
			if (!exportFile.exists()) {
				System.out.println("Export file does not exist - FIXME");
			}
			IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
			IXMLReader reader = StdXMLReader.fileReader(exportFile.getPath());
			parser.setReader(reader);
			XMLElement xml = (XMLElement)parser.parse();
			IXMLElement puzzle = xml.createElement("puzzle");
			// Add cells part of original puzzle 
			for (int i=0;i<81;i++) {
				NanoSudokuCell cell = (NanoSudokuCell)cells.elementAt(i);
				if (generated) {
					if (cell.isSelected()) puzzle.addChild(cell.toNanoXML());
				}
				else if (cell.getValue() != 0 && cell.getColor().equals(Color.black)) 
					puzzle.addChild(cell.toNanoXML());
			}				
			xml.addChild(puzzle);
			// Then XMLWriter the combined back out
			XMLWriter writer = new XMLWriter(new FileOutputStream(exportFile));
			writer.write(xml,true);
		}
		catch (Throwable tossed) { tossed.printStackTrace(); }
	}
}