package com.aluxoft.earrecognition;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import org.opencv.core.Mat;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.core.Size;
import org.opencv.features2d.DescriptorExtractor;
import org.opencv.features2d.FeatureDetector;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

import java.lang.reflect.Type;
import java.util.Vector;

/**
 * Created by josejuliomartinez on 06/10/15.
 */
public class EarIdentifier {

    private EarDatabase database;

    public EarIdentifier(EarDatabase _database) {
        this.database = _database;
    }

    public void setDatabase(EarDatabase _database) {
        this.database = _database;
    }

    /**
     * Do the ear identification process.
     * @param feature The result of the identification.
     * @return
     */
    public EarIdentifierResult identify(EarFeature feature) {
        return null;
    }


    public String computeFeatures(String imagePath) {

        Mat image, descriptors;
        MatOfKeyPoint keypoints;

        descriptors = new Mat();
        keypoints = new MatOfKeyPoint();

        image = Highgui.imread(imagePath, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
        FeatureDetector detector = FeatureDetector.create(FeatureDetector.SIFT);
        detector.detect(image, keypoints);
        DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.SIFT);
        extractor.compute(image, keypoints, descriptors);

        Vector<Integer> features = new Vector<Integer>();
        for (int i=0;i<descriptors.rows();++i) {
            features.add((int)descriptors.get(i, 0)[0]);
        }
        Gson gson = new Gson();
        return gson.toJson(features);
    }

    static {
        System.loadLibrary("opencv_java");
        System.loadLibrary("nonfree");
    }

    private void resizeMat(Mat image) {
        final double kMaxWidth = 160;
        final double kMaxHeight = 120;

        if (image.width() <= kMaxWidth && image.height() <= kMaxHeight) {
            return;
        }

        double ratio = (double)image.width() / (double)image.height();
        double width, height;
        if (ratio > 1) {
            width = kMaxWidth;
            height = kMaxWidth * ((double)image.height()/(double)image.width());
        } else {
            height = kMaxHeight;
            width = kMaxHeight* ratio;
        }
        Imgproc.resize(image, image, new Size(width, height));
    }

}
