package seed.minerva.optics.pointSpread;

import java.util.List;

import cache.randomAccessCache.RACache;
import cache.randomAccessCache.RACacheService;

import binaryMatrixFile.BinaryMatrixFile;

import oneLiners.OneLiners;
import seed.minerva.MinervaOpticsSettings;
import seed.minerva.optics.Util;
import seed.minerva.optics.interfaces.Absorber;
import seed.minerva.optics.optics.Box;
import seed.minerva.optics.pointSpread.PSFGrid;
import seed.minerva.optics.pointSpread.PSFStatsSourceInterpolation;
import seed.minerva.optics.pointSpread.PointSpreadFunction;

/** Generate images from PSF interpolation generated by GeneratePSFInterpolationExample  */
public class PSFImagingExample {
	
	final static String outPath = MinervaOpticsSettings.getAppsOutputPath() + "/rayTracing/imgTest";
	
	//Grids as used in SimpleImaging
	final static String psfSet = "imgTest";  //should match the one in GeneratePSFInterpolationExample
	
	final static double imageX[] = OneLiners.linSpace(-0.015, 0.015, 500);
	final static double imageY[] = OneLiners.linSpace(-0.015, 0.015, 500);
		
	public static void main(String[] args) {
		PSFGrid psfGrid = new PSFGrid(psfSet);
		
		PSFStatsSourceInterpolation psfInterp = new PSFStatsSourceInterpolation(psfGrid);
		
		reimageGrid(psfInterp);
		//if(true)return;
		
		Box box = new Box("box", new double[]{ 0, 0, 0}, 0.200, 0.200, 0.200, null, Absorber.ideal());
		Util.rotateOnX(box, new double[]{0,0,0}, 10*Math.PI/180);
		Util.rotateOnY(box, new double[]{0,0,0}, -30*Math.PI/180);
		Util.rotateOnZ(box, new double[]{0,0,0}, 45*Math.PI/180);
		
		reimage(psfInterp, Util.drawingToPoints(box.draw(), 0.0001));
		
	}
	
	public static void reimage(PSFStatsSourceInterpolation psfInterp, double obj[][]){
		
		double image[][] =  new double[imageX.length][imageY.length];
		
		for(int i=0; i < obj.length; i++) {
			PointSpreadFunction psf = psfInterp.getInterpolatedPSF(obj[i][0], obj[i][1], obj[i][2]);
			
			//PointSpreadFunction psf = psfColl.getPSFExact(new double[]{ gX[3], gY[iX], gZ[iY] });
			if(psf != null)
				psf.addToGrid(imageX, imageY, image, 1);
				
			System.out.print(".");
		}
		
		BinaryMatrixFile.mustWrite(outPath + "/reimageBox.bin", imageX, imageY, image, false);
		
	}
	
	public static void reimageGrid(PSFStatsSourceInterpolation psfInterp){
		double x[] = OneLiners.linSpace(-1.500, 1.500, 50);
		double y[] = OneLiners.linSpace(-1.500, 1.500, 50);
		
		double image[][] =  new double[imageX.length][imageY.length];
		
		for(int iX=0; iX < x.length; iX++) {
			for(int iY=0; iY < y.length; iY++) {
				PointSpreadFunction psf = psfInterp.getInterpolatedPSF(0.0, x[iX], y[iY]);
				
				//PointSpreadFunction psf = psfColl.getPSFExact(new double[]{ gX[3], gY[iX], gZ[iY] });
				if(psf != null)
					psf.addToGrid(imageX, imageY, image, 1);
			}	
			System.out.print(".");
		}
		
		BinaryMatrixFile.mustWrite(outPath + "/reimage.bin", imageX, imageY, image, false);
		
	}		
}
