package org.genericsystem.cv;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.opencv.core.MatOfPoint;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class Zones {
	private final List<Zone> zones;
	private static final ObjectMapper mapper = new ObjectMapper();

	public static Zones get(Img img, double minArea) {
		return new Zones(img, minArea);
	}

	public static Zones get(Img img, double minArea, double dx, double dy) {
		return new Zones(img, minArea).adjust(dx, dy, img.width(), img.height());
	}

	private Zones adjust(double dx, double dy, int width, int height) {
		return new Zones(
				zones.stream().map(zone -> zone.adjustRect(dx, dy, width, height)).collect(Collectors.toList()));
	}

	public Zones(List<Zone> zonesList) {
		this.zones = zonesList;
	}

	public Zones(Img gray, double minArea) {
		this.zones = new ArrayList<>();
		List<MatOfPoint> contours = gray.findContours(new Img[1], Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
		for (int i = 0; i < contours.size(); i++) {
			MatOfPoint contour = contours.get(i);
			double contourarea = Imgproc.contourArea(contour);
			if (contourarea > minArea) {
				Rect rect = Imgproc.boundingRect(contour);
				if (rect.width >= rect.height)
					zones.add(new Zone(rect));
			}
		}
	}

	public List<Zone> get() {
		return zones;
	}

	public void draw(Img img, Scalar scalar, int thickness) {
		zones.forEach(adjusted -> adjusted.draw(img, scalar, thickness));
	}

	public List<Zone> getZones() {
		return zones;
	}

	public void save(File file) {
		file.getParentFile().mkdirs();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
		try {
			mapper.writeValue(file, zones);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	// public void load(File file) throws JsonParseException,
	// JsonMappingException, IOException {
	// zones = mapper.readValue(file, Zones.class);
	// }

}

@@ -292,16 +292,130 @@
 gproc;%0A%0A
+import com.fasterxml.jackson.core.JsonParseException;%0Aimport com.fasterxml.jackson.databind.JsonMappingException;%0A
 import c
@@ -458,16 +458,16 @@
 Mapper;%0A
-
 import c
@@ -540,16 +540,16 @@
 Zones %7B%0A
+
 %09private
@@ -549,22 +549,16 @@
 private 
-final 
 List%3CZon
@@ -2010,21 +2010,87 @@
 e(file, 
-zones
+this);%0A%09%09%09System.out.println(%22Zones saved in %22 + file.getAbsolutePath()
 );%0A%09%09%7D c
@@ -2154,27 +2154,26 @@
 %09%09%7D%0A
+%0A
 %09%7D%0A%0A%09
-// 
 public 
-void
+Zones
  loa
@@ -2211,20 +2211,16 @@
 ception,
-%0A%09//
  JsonMap
@@ -2253,18 +2253,15 @@
  %7B%0A%09
-// zones =
+%09return
  map
@@ -2299,11 +2299,8 @@
 );%0A%09
-// 
 %7D%0A%0A%7D

Save and load zones