package image;

import java.awt.Font;
import java.util.ArrayList;

import math.number.NumberComplex;
import stdlib.Color;
import stdlib.StdDraw;

public class Trajectory {
	static StdDraw sd = new StdDraw();

    // return number of iterations to check if c = a + ib is in Mandelbrot set
    public static boolean mand(NumberComplex z0, int d) {
        sd.setPenColor(Color.RED);
        NumberComplex z = z0;
        StdDraw.filledCircle(z.ℜ(), z.ℑ(), .025);
        sd.setPenColor(Color.BLUE);
        NumberComplex zold = z;
        for (int t = 0; t < d; t++) {
            if (z.mod() >= 2.0) return false;
            zold = z;
            z = z.times(z).plus(z0);
            StdDraw.filledCircle(z.ℜ(), z.ℑ(), .01);
            sd.line(zold.ℜ(), zold.ℑ(), z.ℜ(), z.ℑ());
        }
        return true;
    }

    public static void main(String[] args) {
       ArrayList<NumberComplex> black = new ArrayList<NumberComplex>();
       ArrayList<NumberComplex> white = new ArrayList<NumberComplex>();
       sd.setXscale(-2, 2);
       sd.setYscale(-2, 2);
       StdDraw.setFont(new Font("Arial", Font.PLAIN, 10));
       StdDraw.clear(Color.LIGHT_GRAY);
       sd.circle(0, 0, 2);
 
       while (true) {
            if (StdDraw.mousePressed()) {
                StdDraw.clear(Color.LIGHT_GRAY);

                // draw the points already computed to be in/outside the set
                sd.setPenColor(Color.BLACK);
                for(NumberComplex z : black) {
                    StdDraw.filledCircle(z.ℜ(), z.ℑ(), .01);
                }
                sd.setPenColor(Color.WHITE);
                for (NumberComplex z : white) {
                    StdDraw.filledCircle(z.ℜ(), z.ℑ(), .01);
                }

                double x = StdDraw.mouseX();
                double y = StdDraw.mouseY();
                NumberComplex z = new NumberComplex(x, y);
                sd.setPenColor(Color.BLACK);
                sd.circle(0, 0, 2);
                StdDraw.text(0, -2.1, z + "");
                if (mand(z, 100)) black.add(z);
                else              white.add(z);
            }
            sd.show(50);
        }
    }
}

