/*
 *  Brno University of Technology
 *
 *  Copyright (C) 2009-2010 by Brno University of Technology and the contributors
 *
 *  Complete list of developers available at our web site:
 *
 *       http://spl.utko.feec.vutbr.cz
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/.
 */
package cz.vutbr.feec.utko.opencv.operators.imageProcessing;

import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;



import ij.plugin.Memory;
import ij.process.ImageProcessor;

import java.awt.image.BufferedImage;
import java.util.List;

import com.googlecode.javacpp.IntPointer;
import com.googlecode.javacpp.Pointer;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.operator.ports.metadata.GenerateNewMDRule;
import com.rapidminer.operator.ports.metadata.MetaData;
import com.rapidminer.operator.ports.metadata.SimplePrecondition;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeCategory;
import com.rapidminer.parameter.ParameterTypeDouble;
import com.rapidminer.parameter.ParameterTypeInt;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.LongByReference;

import cz.vutbr.feec.imageprocessing.IOObject.PointsIOObject;
import cz.vutbr.feec.imageprocessing.IOObject.innerObject.InterrestArea;
import cz.vutbr.feec.utko.opencv.io.OpenCVIOObject;


public class ConvexHullMask extends Operator {

	protected InputPort inPoints = getInputPorts().createPort("points");
	protected OutputPort outPointsImg = getOutputPorts().createPort("image");

	
	public ConvexHullMask(OperatorDescription description) {
		super(description);
		
		inPoints.addPrecondition(new SimplePrecondition(inPoints, new MetaData(
				PointsIOObject.class)));
		
		getTransformer().addRule(
				new GenerateNewMDRule(outPointsImg, OpenCVIOObject.class));
		
	}
	

	
	public final void doWork() throws OperatorException
	{
		PointsIOObject original1 = inPoints.getData();

		int sample_count = original1.getSize();
	
		CvMemStorage storage = CvMemStorage.create();

        // Contiguous regions of native memory may be allocated using createArray() factory methods.
        int sizeofCvContour = com.sun.jna.Native.getNativeSize(CvContour.class);
        int sizeofCvPoint = com.sun.jna.Native.getNativeSize(CvPoint.class);        
        CvSeq contour = CvSeq.create(CV_32SC2, sizeofCvContour, sizeofCvPoint, storage);

        for (InterrestArea interrestArea : original1) {
        	int x = interrestArea.getX();
        	int y = interrestArea.getY();
        	CvPoint pp = new CvPoint(x, y);
        	System.out.println(pp.x() + " " + pp.y());

        	/* TODO: toto nevim jak zprovoznit do OpenCV2.2
        	Pointer p = new com.sun.jna.Memory(sizeofCvPoint*2);
        	p.setInt(0, x);
        	p.setInt(4, y);
        	cvSeqPush(contour, p);
        	*/
		}
        
		CvMat m = CvMat.take(sample_count, 1, CV_MAKE_TYPE(CV_32S, 1));
		cvConvexHull2(contour, m, CV_CLOCKWISE, 0);
		
		IplImage outImg = cvCreateImage( cvSize(original1.getWidth(), original1.getHeight()), IPL_DEPTH_8U, 3 );
		cvSet(outImg, (cvScalar(255,255,255,255)));
		
	//	System.out.println("--------------------");
		
		int pocet = m.rows();
		for (int i = 0; i < m.rows(); i++)
		{
			int x =(int)m.get(0, i, 0); 
			if (x > contour.total())
			{
				pocet = i;
				break;
			}
		}		
		
		CvPoint last = null;
		for (int i = 0; i < pocet+1; i++)
		{
			int x =(int)m.get(0, i%pocet, 0); 
			
			System.out.println(x);
			if (x > contour.total())
				continue;
			
			IntPointer p = null;
			p = (IntPointer) cvGetSeqElem(contour, x);
			CvPoint bod = new CvPoint(p.position(i).get(), p.position(i).get());
			
			//System.out.println(x + " " + y);
		//	CvPoint ppp = new CvPoint((int)x, (int)y);
			CvScalar s = cvScalar(0,0,0,0);
			cvCircle(outImg, bod, 2, s, 2, 1, 0);
			if (last != null)
				cvLine(outImg, last, bod, s, 1, 1, 0);
			
			last = bod;
		}
		
		cvFloodFill(outImg, cvPoint(1,1), cvScalar(0, 0, 0, 0), cvScalarAll(5), cvScalarAll(5), null, 4, null);
		
		OpenCVIOObject out = new OpenCVIOObject(outImg);//(original1.getWidth(), original1.getHeight(), 0, 0);
		
		outPointsImg.deliver(out);
	}
	
	
	@Override
	public List<ParameterType> getParameterTypes()
	{ 
		List<ParameterType> types = super.getParameterTypes();
		return types;
	}

}
