package org.cmdline.sudoku;

import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Vector;
import java.util.Stack;

// Convert puzzle to image for embedding in PDF

public class PuzzleImage {
	File tmp_img = null;
	int index = 0,value = 0;
	boolean colorFirst = false;
	
	public PuzzleImage(BufferedImage puzzle) {
//	public PuzzleImage(Vector cells,Stack solution) {
		try {

/*
			int width = 45*9+1, height = 45*9+1;
			BufferedImage puzzle = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = (Graphics2D)puzzle.getGraphics();
			g2d.setColor(Color.white);
			g2d.fillRect(0,0,45*9+1,45*9+1);
			g2d.setColor(Color.black);

			for (int i=0;i<10;i++) 
				g2d.drawLine(i*45,0,i*45,45*9);
			for (int i=0;i<9;i++)
				g2d.drawLine(0,i*45,45*9,i*45);

		    for (int i=0;i<9;i++) {
		    	int row = i / 9;
		    	int col = i % 9;
		    	System.out.println("row: " + row + " col: " + col + " (" + (col*45+3) + "," + (row*45+3) + ") (" + (col*45+42) + "," + (row*45+42) + ")");
		    	
		    	g2d.drawRect(col*45+3,row*45+3,col*45+42,row*45+42);
		    }
		   if (false)
			for (int i=0;i<cells.size();i++) {
				SudokuCell cell = (SudokuCell)cells.elementAt(i);
				index = cell.getIndex();
				Color c = cell.getColor();
				colorFirst = cell.colorFirst;
//				frameIt(g2d,c);
				int row = index / 9;
				int col = (index+9) % 9;
				value = cell.getValue();
				if (value != 0) {
					g2d.setColor(c);
					Font f = g2d.getFont().deriveFont(18f);
					if (!SolvingSudokuBoard.solving) 
						f = f.deriveFont(Font.BOLD);
					g2d.setFont(f);
//					int xinc = (((col+4)%3)*2)+(col/3*3);
//					int yinc = (((row+4)%3)*2)+(row/3*3);
					g2d.drawString(new Integer(value).toString(),col*45+14,row*45+24);
				}
			}
*/
			tmp_img = File.createTempFile("sudoku","jpg");
			ImageIO.write(puzzle,"JPG",tmp_img);
		}
//		catch (java.io.IOException ioex) { ioex.printStackTrace(); }
		catch (Throwable tossed) { tossed.printStackTrace(); }
	}
	
	private void frameIt(Graphics2D g,Color c) {
		if (colorFirst) 
			g.setColor(c);
		else
			g.setColor(Color.black);
		int row = index / 9;
		int col = (index+9) % 9;
//		int xinc = (((col+4)%3)*2)+(col/3*3);
//		int yinc = (((row+4)%3)*2)+(row/3*3);
		g.drawRect(col*45+3,row*45+3,col*45+42,row*45+42);
/*
		if ((col + 3) % 3 == 0) 
			g.drawLine(col*45+1,row*45,col*45+1,row*45+44);
		if ((col + 3) % 3 == 2)
			g.drawLine(col*45+43,row*45,col*45+43,row*45+44);
		if ((row + 3) % 3 == 0)
			g.drawLine(col*45,row*45+1,col*45+44,row*45+1);
		if ((row + 3) % 3 == 2)
			g.drawLine(col*45,row*45+43,col*45+44,row*45+43);
*/

		g.setColor(c);
	}
	
	public URL getImageURL() { 
		try {
			return new URL(new StringBuffer("file://localhost").append(tmp_img).toString()); 
		}
		catch (Throwable tossed) {
			tossed.printStackTrace(); 
		}
		return null;
	}
}