package math.fractals;

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import math.utils.*;

public class Fractal05 extends JFrame{
	private static final long serialVersionUID = 431281611636634328L;
	public static final int fw = 1000;
	public static final int fh = 1000;

	public static void main(String[] args) {
		SwingUtilities.invokeLater(() -> new Fractal05(new SierpinskiRandomPanel(200000)));
	}

	public Fractal05(JComponent comp){
		setLayout(null);
		setPreferredSize(new Dimension(fw, fh));
		setBounds((Toolkit.getDefaultToolkit().getScreenSize().width / 2)
				- (fw / 2),
				(Toolkit.getDefaultToolkit().getScreenSize().height / 2)
						- (fh / 2), fw, fh);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("Ramka Graficzna");
		//	setResizable(false);
		JPanel panel = (JPanel) comp;
		panel.setLocation((fw - panel.getWidth()) / 2,
				(fh - panel.getHeight()) / 2);
		add(panel);
		setVisible(true);
	}
}

class SierpinskiRandomPanel extends JPanel{
	private static final long serialVersionUID = 5218506428064759030L;
	private static final int w = 800;
	private static final int h = 800;
	private final int steps;
	private final Point A;
	private final Point B;
	private final Point C;
	private Point D;
	private Point srodek;

	public SierpinskiRandomPanel(int steps){
		this.steps = steps;
		setPreferredSize(new Dimension(w, h));
		setSize(w, h);
		setBackground(Color.WHITE);
		A = new Point(0, w);
		B = new Point(w, w);
		C = new Point(w / 2, w - (int)(w * Math.sqrt(3) / 2));
		D = new Point(200, 750);
		srodek = null;
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		BufferedImage bimage = new BufferedImage(w, w, BufferedImage.TYPE_INT_ARGB);
		WritableRaster raster = bimage.getRaster();
		int[] rgb = new int[4];
		rgb[0] = 0;
		rgb[1] = 0;
		rgb[2] = 255;
		rgb[3] = 255;
		for(int i = 0; i < steps; i++){
			int r = MathUtil.randomInRange(0, 2);
			switch(r){
				case 0:
					srodek = srodek(D, A);
					break;
				case 1:
					srodek = srodek(D, B);
					break;
				case 2:
					srodek = srodek(D, C);
					break;
			}
			raster.setPixel(srodek.x, srodek.y, rgb);
			D = srodek;
		}
		g.drawImage(bimage, 0, 0, this);
	}

	public static Point srodek(Point p1, Point p2) {
		return new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
	}
}