package com.elphel.imagej.orthomosaic;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;

import ij.Prefs;

public class GroundObjectPattern implements Serializable {
	private static final long serialVersionUID = 1L;	
	public static long UTC_EAST_HRS = 3;
	public static String  patterns_directory;
	//public LocalDateTime plusHours(long hours) 	
	public int     zoom_level;     // 1 for 5mm/pix 
	public String  object_type;    // like "TM62"
//	public String  object_version; // just change config 
	LocalDateTime  utcDateTime;    // UTC
	public String  filename;       // should be square
	
	public GroundObjectPattern(
			String        filename,
			int           zoom_level,
			String        object_type,
			LocalDateTime utcDateTime) {
		this.filename =    filename;
		this.zoom_level =  zoom_level;
		this.object_type = object_type;
		this.utcDateTime = utcDateTime;
	}
	private void writeObject(ObjectOutputStream oos) throws IOException {
		oos.defaultWriteObject();
	}
	private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
		ois.defaultReadObject();
	}
	
	public static void setPatternsDirectory(
			String directory) {
		while (directory.endsWith(Prefs.getFileSeparator())){
			directory=directory.substring(0, directory.length()-1);
		}
		patterns_directory = directory;
	}
	
	public String getPatternPath() {
		return patterns_directory+Prefs.getFileSeparator()+filename;
	}
	
	public static String getPatternsDirectory() {
		return patterns_directory;
	}
	
	public static GroundObjectPattern getPattern(
			String        object_type,
			LocalDateTime utcDateTime,
			ArrayList<GroundObjectPattern> patterns) {
		GroundObjectPattern best_gop = null;
		long best_hrs_diff = 24;
		for (GroundObjectPattern gop:patterns) {
			if ((object_type == null) || object_type.equals(gop.object_type)) {
				if (utcDateTime != null) {
					long hrs_diff = Math.abs(utcDateTime.getHour()-gop.utcDateTime.getHour());
					if (hrs_diff > 12) {
						hrs_diff = 24 -hrs_diff;
					}
					if (hrs_diff < best_hrs_diff) {
						best_gop = gop; 
						best_hrs_diff = hrs_diff;
					}
				} else {
					best_gop = gop; // use latest
				}
			}
		}
		return best_gop;
	}
	
	public LocalDateTime getUTC() {
		return utcDateTime;
	}
	public LocalDateTime getLocalDT() {
		return utcDateTime.plusHours(UTC_EAST_HRS);
	}
	public boolean isEvening() {
		return getLocalDT().getHour() >= 12;
	}
	
	public double getAGL() {
		double agl = 50; // zoom 0 for 50m AGL
		for (int z = zoom_level; z > 0; z--) {
			agl /=2;
		}
		for (int z = zoom_level; z < 0; z++) {
			agl *=2;
		}
		return agl;
	}
	
	public int getZoomLevel() {
		return zoom_level;
	}
}
