package lpv.simulation.injector;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.vecmath.Vector4f;

import lpv.LPV;

public class FileInjector implements Injector {
	
	private String file;
	private float strength;

	public FileInjector(float strength, String file) {
		this.strength = strength;
		this.file = file;
	}
	
	@Override
	public void inject(LPV lpv) {
		try {
			String[] paths = file.split(File.pathSeparator);
			for(String path : paths) {
				BufferedReader br = new BufferedReader(new FileReader(path));
				
				String line = br.readLine();
				String[] parts = line.split(",");
				int w = Integer.parseInt(parts[0]);
				int h = Integer.parseInt(parts[1]);
				int d = Integer.parseInt(parts[2]);
				
				if(w != lpv.getWidth(0) || h != lpv.getHeight(0) || d != lpv.getDepth(0)) {
					throw new RuntimeException("Size of input LPV (" + w + "," + h + "," + d + ") does not " +
							"match size of runtime.");
				}
				
				for(int z = 0; z < d; z++) {
					for(int y = 0; y < h; y++) {
						line = br.readLine();
						parts = line.split(",");
						for(int x = 0; x < w; x++) {
							Vector4f sh = new Vector4f();
							sh.x = Float.parseFloat(parts[4*x + 0]);
							sh.y = Float.parseFloat(parts[4*x + 1]);
							sh.z = Float.parseFloat(parts[4*x + 2]);
							sh.w = Float.parseFloat(parts[4*x + 3]);
							sh.scale(strength);
							lpv.get(0, x, y, z).add(sh);
						}
					}
				}
				
				br.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Override
	public String toString() {
		String fileShort = file;
		if(fileShort.length() > 20) {
			fileShort = "..." + fileShort.substring(fileShort.length()-20);
		}
		return "File injector (" + fileShort + ")";
	}

}
