/* ----------------------------------------
 * Origin  : GFI INFORMATIQUE 
 * Project : CDPP Propagation Tool 
 * ----------------------------------------
 * History 
 * Version : 01/05/2015 : SCA : V2.1
 * ----------------------------------------
 */
package fr.tlse.irap.shock;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class ShockWrapper {

	private List<Shock> shocks;

	public ShockWrapper() {
		this.setShocks(new ArrayList<Shock>());
	}

	public ShockWrapper(List<Shock> shocks) {
		this.setShocks(shocks);
	}

	@XmlElement
	public List<Shock> getShocks() {
		return shocks;
	}

	public void setShocks(List<Shock> shocks) {
		this.shocks = shocks;
	}

	public Shock getNearestFromTime(Date date) {
		//if (shocks.isEmpty() || date.before(shocks.get(0).getShockTime())) {
		if (shocks.isEmpty() || shocks.size() < 2) {
			return null;
		}
		Shock prev = (shocks.get(0));
		Shock next = null;
		
		for (Shock shock : this.shocks) {
			if (shock.getShockTime().after(date)) {
				next = shock;
				break;
			}
			prev = shock;
		}

		if (next != null) {	
			long deltaPrev = Math.abs(prev.getShockTime().getTime() - date.getTime());
			long deltaNext = Math.abs(next.getShockTime().getTime() - date.getTime());
			long deltaTime = shocks.get(1).getShockTime().getTime() - shocks.get(0).getShockTime().getTime();
			
			if (deltaPrev < deltaNext) {
				if (deltaPrev < deltaTime) {
					return prev;
				}
			}
			else {
				if (deltaNext < deltaTime) {
					return next;
				}
			}
		}
		// in other cases return null
		return null;
	}

}

