package io.github.jjsimas.chart2d;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;

public abstract class ResponsiveChart extends JComponent {

  protected ResponsiveChart() {
    setOpaque(true);
  }

  public final BufferedImage renderImage(Dimension size) {
    BufferedImage image = new BufferedImage(
      Math.max(1, size.width),
      Math.max(1, size.height),
      BufferedImage.TYPE_INT_ARGB
    );
    Graphics2D g2 = image.createGraphics();
    try {
      configureGraphics(g2);
      paintChart(g2, image.getWidth(), image.getHeight());
    }
    finally {
      g2.dispose();
    }
    return image;
  }

  protected final Graphics2D createMeasurementGraphics() {
    BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    configureGraphics(g2);
    return g2;
  }

  protected static void configureGraphics(Graphics2D g2) {
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
  }

  @Override
  protected final void paintComponent(Graphics graphics) {
    Graphics2D g2 = (Graphics2D) graphics.create();
    try {
      configureGraphics(g2);
      paintChart(g2, getWidth(), getHeight());
    }
    finally {
      g2.dispose();
    }
  }

  protected abstract void paintChart(Graphics2D g2, int width, int height);
}
