package fr.tlse.irap.pt.client.controller.common;

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

import fr.tlse.irap.pt.client.controller.tools.carrington.CarringtonHelper;
import fr.tlse.irap.flare.Flare;
import fr.tlse.irap.pt.client.services.ServiceFactory;
import fr.tlse.irap.spaceElement.Planet;
import fr.tlse.irap.tool.radial.CMEType;
import fr.tlse.irap.utils.CoordConverter;

public class FlareCollection{

	public final static long DELTA_DAYS = 1;
	
	private static List<Flare> flares;
	private final static Date currentDate = new Date();
	public static String obs = "STEREO-A";
	public static CMEType cmeType = CMEType.SSE;
	public static boolean isLinkcat = false;
	
	public static void init() {
		obs = "STEREO-A";
		cmeType = CMEType.SSE;
		isLinkcat = false;		
	}
	
	/**
	 * Unique access web service call to get flare list around date (+ or - DELTA_DAYS)
	 * @return
	 */
	public static List<Flare> getFlaresAround(Date date) {
		synchronized (currentDate) {
			if (currentDate == null || !date.equals(currentDate)) {
				Date startDate = new Date();
				long deltaTime = DELTA_DAYS * 86400 * 1000;
				startDate.setTime(date.getTime() - deltaTime);
				Date endDate = new Date();
				endDate.setTime(date.getTime() + deltaTime);
				if (isLinkcat) {
					flares = ServiceFactory.getFlareService().fetchLinkcatFlares(startDate, endDate, cmeType, obs).getFlares();
				}
				else {
					flares = ServiceFactory.getFlareService().fetchFlares(startDate, endDate).getFlares();
				}
				flares = computeFlaresLongitudes(flares);
				currentDate.setTime(date.getTime());
			}
		}
		return flares;
	}
	
	/**
	 * Compute the flares longitudes for display
	 */
	private static List<Flare> computeFlaresLongitudes(List<Flare> flares) {
		double currentMeridian[] = null;
		Date currentDayDate = null;
		Planet earth = new Planet("EARTH");

		for (Flare flare : flares) {
			if (!flare.getDayDate().equals(currentDayDate)) {
				currentDayDate = flare.getDayDate();
				currentMeridian = CarringtonHelper.computeCarringtonCoordinates(earth, currentDayDate, true);
			}
			if (currentMeridian != null) {
				flare.setCentralLongitude(currentMeridian[0]);
				flare.setDisplayLongitude(CoordConverter.normalizeLongitude(currentMeridian[0] + flare.getRelativeLongitude()));
			}
		}
		return flares;
	}

}
