package math.fractals;

import math.utils.Tuple2d;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;

public class Fractal06 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 Fractal06(new BarnsleyPanel(100000)));
    }

    public Fractal06(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 BarnsleyPanel 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 Tuple2d[] arr;
    private final int[] rgb = {0, 255, 0, 255};

    public BarnsleyPanel(int steps) {
        this.steps = steps;
        arr = FractalUtil.calculateBarnsley(steps);
        setPreferredSize(new Dimension(w, h));
        setSize(w, h);
        setBackground(Color.WHITE);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        BufferedImage bimage = new BufferedImage(w, w, BufferedImage.TYPE_INT_ARGB);
        WritableRaster raster = bimage.getRaster();
        for (Tuple2d tuple2d : arr) {
            int x = (int) (tuple2d.getX() * 50) + 3 * 50;
            int y = (int) (tuple2d.getY() * 50) + 3 * 50;
            raster.setPixel(y, x, rgb);
        }
        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);
    }

    public int getSteps() {
        return steps;
    }
}