package presenter.evaluation;
import model.Line;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.*;
import org.opencv.imgproc.Imgproc;
import presenter.Presenter;
import presenter.algorithms.advanced.LeastMedianOfSquaresEstimator;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;

/**
 * Implementierung verschiedener Algorithmen zur Berechnung von Ausgleichsgeraden.
 *
 * @Author: Armin Wolf
 * @Email: a_wolf28@uni-muenster.de
 * @Date: 17.09.2017.
 */
public class PictureProcessor extends Observable{

    private Mat image;
    private Mat threshold;
    private Presenter presenter;
    private File file;

    public PictureProcessor(Presenter presenter, File file)  {
        this.file = file;
        this.presenter = presenter;
    }

    public void run(){
        String msg = "";
        msg = SwingUtilities.isEventDispatchThread() ?  "EDT" : "nicht EDT";
        System.out.println(msg);

        System.out.println("Welcome to OpenCV " + Core.VERSION);

        image = Highgui.imread(file.getAbsolutePath());
        threshold = process(image);
        createInputData(threshold);
    }

    private Mat process(Mat image){
        threshold = new Mat(image.width(), image.height(), CvType.CV_8UC1);
        Mat source = new Mat(image.width(), image.height(), CvType.CV_8UC1);
        Imgproc.cvtColor(image, source, Imgproc.COLOR_BGR2GRAY);
        Imgproc.adaptiveThreshold(source, threshold,255, Imgproc.ADAPTIVE_THRESH_MEAN_C,
                                  Imgproc.THRESH_BINARY_INV, 11,2);
        return threshold;
    }


    private BufferedImage toBufferedImage(Mat m) {
        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (m.channels() > 1) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        int bufferSize = m.channels() * m.cols() * m.rows();
        byte[] b = new byte[bufferSize];
        m.get(0, 0, b); // get all the pixels
        BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
        final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        System.arraycopy(b, 0, targetPixels, 0, b.length);
        return image;

    }

    private void createInputData(Mat image){
        Thread t = new Thread(() -> {
            int id = 0;
            for (int i=0;i<image.rows();i++){
                for (int j=0;j<image.cols();j++){
                    double[] colVal = image.get(i,j);
                    if (colVal[0] == 255d){
                        Line line = new Line(i,j);
                        line.setId(""+id++);
                        presenter.getModel().getLines().add(line);
                    }
                }
            }
        });
        t.start();
        try {
            t.join();
            setChanged();
            String[] msg = {"import-picture"};
            notifyObservers(msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}