package ac.essex.ooechs.facedetection.util.evaluation;

import ac.essex.ooechs.imaging.commons.HaarRegions;
import ac.essex.ooechs.imaging.commons.Pixel;
import ac.essex.ooechs.imaging.commons.PixelLoader;
import ac.essex.ooechs.imaging.commons.util.ImageFilenameFilter;
import ac.essex.ooechs.facedetection.util.AbstractDetectionProblem;

import java.util.Vector;
import java.awt.*;
import java.io.File;

public abstract class ObjectDetector {

    public static final int NOT_OBJECT = 0;
    public static final int OBJECT = 1;

    public abstract double calculate(int x, int y, int windowWidth, int windowHeight, PixelLoader image);

    public void test(File directory) throws Exception {
        int counter = 0;
        int hits = 0;
        File[] trueFiles = directory.listFiles();
        for (int i = 0; i < trueFiles.length; i++) {
            File f = trueFiles[i];
            if (ImageFilenameFilter.isImage(f)) {
                PixelLoader image = new PixelLoader(f);
                double raw = calculate(0,0,image.getWidth(), image.getHeight(), image);
                if (raw > 0) hits++;
                counter++;
            }
        }
        double percentage = hits / (double) counter;
        System.out.println(directory.getName() + " " + hits + " / " + counter + " = " + percentage);
    }

    public Vector<Pixel> getObjects(PixelLoader image, int windowWidth, int windowHeight) {

        Vector<Pixel> objects = new Vector<Pixel>(10);

        boolean[][] detectionMap = new boolean[image.getWidth()][image.getHeight()];

        for (int y = 0; y < (image.getHeight() - 20); y += 1) {
            for (int x = 0; x < (image.getWidth() - 20); x += 1) {

                if (calculate(x,y,windowWidth, windowHeight, image) > 0) {
                    detectionMap[x][y] = true;
                    objects.add(new Pixel(x, y));
                }

            }

        }
/*
        for (int y = 1; y < (image.getHeight() - 20); y += 2) {
            for (int x = 1; x < (image.getWidth() - 20); x += 2) {

                if (detectionMap[x][y]) {

                    int neighbourCount = 0;

                    // count neighbours
                    for ( int dY = -1; dY <= 1; dY++ ) {
                        for ( int dX = -1; dX <= 1; dX++ ) {
                            if (detectionMap[x + dX][y + dY]) neighbourCount++;
                        }
                    }

                    if (neighbourCount >= 9) {
                        objects.add(new Pixel(x, y));
                    }

                }

            }
        }*/

        return objects;

    }

    public void drawObjects(Vector<Pixel> objects, HaarRegions image, Graphics g) {
        for (int i = 0; i < objects.size(); i++) {
            Pixel object = objects.elementAt(i);
            g.setColor(Color.white);
            g.drawRect(object.x, object.y, image.getWindowWidth(), image.getWindowHeight());
        }
    }

}