package jlama;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;

public class WaveProgressIcon implements Icon {
    private static final int WIDTH = 16;
    private static final int HEIGHT = 10;

    private static final int PERIOD_MS = 1500;
    private static final int TIMER_DELAY_MS = 40;

    private float phase = 0f;

    public static void applyToLabel(JLabel label) {
        WaveProgressIcon icon = new WaveProgressIcon(label);
        label.setIcon(icon);
        Timer timer = new Timer(TIMER_DELAY_MS, (ActionEvent e) -> {
            icon.updateAnimation();
            label.repaint();
        });
        timer.start();
    }

    private WaveProgressIcon(JLabel label) {
        label.setIcon(this);
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2 = (Graphics2D)g.create();
        try {
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            Color color = UIManager.getColor("Label.disabledForeground");
            g2.setColor(color);
            g2.draw(createPath(x, y));
        } finally {
            g2.dispose();
        }
    }

    private Path2D createPath(int x, int y) {
        int midY = y + HEIGHT / 2;
        int startX = x + 2;
        int endX = x + WIDTH - 2;

        double maxAmplitude = (HEIGHT / 2.0) - 2;
        double amplitude = maxAmplitude * Math.sin(2 * Math.PI * phase);

        float totalWidth = endX - startX;
        float step = totalWidth / 4.0f;

        Path2D path = new Path2D.Float();
        path.moveTo(startX, midY);
        path.lineTo(startX + step, midY - amplitude);
        path.lineTo(startX + 2 * step, midY);
        path.lineTo(startX + 3 * step, midY + amplitude);
        path.lineTo(endX, midY);
        return path;
    }

    private void updateAnimation() {
        float step = 1f * TIMER_DELAY_MS / PERIOD_MS;
        phase += step;
        if (phase > 1f) {
            phase -= 1f;
        }
    }

    @Override
    public int getIconWidth() {
        return WIDTH;
    }

    @Override
    public int getIconHeight() {
        return HEIGHT;
    }
}