package physics;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.Scanner;

import stdlib.Color;
import stdlib.Picture;

public class Potential {

	/**
	 * Potential value visualization for a set of charges.
	 * @param filename
	 * @throws FileNotFoundException
	 */
    public void potential(String filename) throws FileNotFoundException {
        // read in N point charges
    	Scanner in = new Scanner(new File(filename), "UTF-8");
    	in.useLocale(new Locale("en", "US"));
    	int n = in.nextInt();
    	double x0, y0, q0;
        Charge[] a = new Charge[n];
        for(int k = 0; k < n; k++) {
            x0 = in.nextDouble();
            y0 = in.nextDouble();
            q0 = in.nextDouble();
            a[k] = new Charge(x0, y0, q0);
        }
        in.close();

        // compute the potential at each point and plot
        int SIZE = 800;
        int i, j, k;
        Picture pic = new Picture(SIZE, SIZE);
        for(i=0; i<SIZE; i++){
            for(j=0; j<SIZE; j++){
                double V = 0.0;
                for(k=0; k<n; k++){
                    double x = 1.0 * i / SIZE;
                    double y = 1.0 * j / SIZE;
                    V += a[k].potentialAt(x, y);
                }
                V = 128 + V / 2.0e10;
                int t = 0;
                if     (V <   0) t = 0;
                else if(V > 255) t = 255;
                else             t = (int) V;
//                Color c = new Color(t, t, t);
                Color c = Color.getHSBColor(
                		.9f*t/255.0f, /*.9 so that both extrema have different colors*/
                		.9f, .9f);
//                Color c = Color.getHSBColor(.75f*t/40, .8f, .8f);
//                int gray = (t * 37) % 255;
//                Color c = new Color(gray, gray, gray);
                pic.set(i, SIZE-1-j, c);
            }
        }
        pic.show();
    }
    
    /**
     * visualizing electric potential
     * @param args
     * @throws FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException{
    	Potential poti = new Potential(); 
    	poti.potential("resources/charges.txt");
    }
}
