package jetbookcolor.scribble;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ScribbleHandler {
	
	protected File f;
	protected InputStream is;
	protected int fileXMax;
	protected int fileYMax;

	protected long numBytesRead;
	protected long numBytesTotal;
	
	public ScribbleHandler(File f) throws IOException{
		if(!f.exists() || !f.isFile()){
			throw new IOException ("Scribble file: " + f.getName() + " does not exist.");
		}
		
		this.f = f;
		is = new FileInputStream(f);
		
		numBytesTotal = f.length();
		numBytesRead = 0;
		
		// parse header
		// header contains [loX, hiX, loY, hiY]
		byte[] header = new byte[4]; 
		
		if(is.read(header) != 4){
			// unable to read the first 4 bytes.
			throw new IOException("Scribble file: " + f.getName() + " . Unable to read the first 4 header bytes");
		}
		
		// TODO: Jetbook Color might have different size header... some bounds checking?
		// Currently, assuming this is plainly 1600x1036
		numBytesRead += 4;
		fileXMax = ((int)(header[3]) << 8) | ((int)header[2] & 0x00ff);
		fileYMax = ((int)(header[1]) << 8) | ((int)header[0] & 0x00ff);
		
		System.out.println("Scribble file: " + f.getCanonicalPath() + ". X: " + fileXMax + " Y: " + fileYMax);
		
	}
	
	public void close() throws IOException{
		if(is != null)
			is.close();
	}
		
	public ScribbleFile getScribbleFile() throws IOException{
		byte[] line = new byte[5];
		ScribbleFile sfile = new ScribbleFile();
		sfile.setVertical(fileXMax);
		sfile.setHorizontal(fileYMax);
		sfile.setPage(Integer.parseInt(f.getName()));
		
		Scribble scribble = new Scribble();
				
		while(is.read(line) == 5){
			numBytesRead += 5;
			
			
			if(line[0] == -1 && line[1] == -1 && line[2] == -1 && line[3] == -1){
				// reached a new line
				if(scribble.size() >= 2) // has to contain at least 2 points
					sfile.add(scribble); // push the completed Scribble into the ScribbleFile's Linked List
				scribble = new Scribble(); // initialize a new (empty) Scribble
			}
			else{ 
				// continue from the previous scribble

				//System.out.println( line[0] + " " + line[1] + " " + line[2] + " " + line[3] + " " + line[4]);
				
				scribble.add(new Point( 
							(((int)(line[1]) << 8) | ((int)line[0] & 0x00ff)) // convert X value to int
							,(((int)(line[3]) << 8) | ((int)line[2] & 0x00ff)) // convert Y value to int
							));
			}
			if(numBytesRead == numBytesTotal){
				// reached the end of the file
				if(scribble.size() >= 2) // has to contain at least 2 points
					sfile.add(scribble); // push the completed Scribble into the ScribbleFile's Linked List
				is.close(); // close inputstream
				return sfile;
			}
		}
		
		throw new IOException("Scribble file: " + f.getName() + " Unable to read completely from file");
	}
	
	
	
}
