package ip.gui.frames;

import ip.gui.dialog.MatLog;
import ip.gui.ConvolutionUtils;

import java.awt.*;

import utils.MyMath;

public class ConvolutionFrame extends OpenFrame {

    ConvolutionFrame(String title) {
        super(title);
    }

    private boolean showKernal = false;

    /**
     Toggles the convolutions kernel boolean
     on and off in the
     @see SpatialFilterFrame
     */
    public void showConvolutionKernal() {
        showKernal = !showKernal;
    }

    public int cx(int x) {
        if (x > getImageWidth() - 1) return x - getImageWidth() + 1;
        if (x < 0) return getImageWidth() + x;
        return x;
    }

    public int cy(int y) {
        if (y > getImageHeight() - 1) return y - getImageHeight() + 1;
        if (y < 0) return getImageHeight() + y;
        return y;
    }


    public void randImage() {
        randImage(0, 255);
    }

    public void randImage(int min, int max) {
        for (int x = 0; x < getImageWidth(); x++)
            for (int y = 0; y < getImageHeight(); y++) {
                getR()[x][y] = (short) MyMath.rand(min, max);
                getG()[x][y] = (short) MyMath.rand(min, max);
                getB()[x][y] = (short) MyMath.rand(min, max);
            }
        short2Image();
    }

    private void showMatLog() {
        Rectangle r = getBounds();
        Dimension d = r.getSize();
        ml.setLocation(d.width, d.height / 2);
        ml.setVisible(true);
    }

    private MatLog ml;

    public void convolve(float k[][]) {
        //super.convolveFast(k);
        convolveSlow(k);
    }

    public void convolveSlow(float k[] []) {
        // a 1kx1k image allocates not more than
        // 1 MB at a time.
        //Mat.print(k);
        //Timer t = new Timer();
        //t.start();
        if (showKernal) {
            ml = new MatLog(k);
            showMatLog();
        }
        setR(ConvolutionUtils.convolve2(getR(), k));
        setG(ConvolutionUtils.convolve2(getG(), k));
        setB(ConvolutionUtils.convolve2(getB(), k));
        getClipper().clip(getR(), getG(), getB());
        short2Image();
        //t.print("convolution done");
    }
}