/* ----------------------------------------
 * Origin  : GFI INFORMATIQUE 
 * Project : CDPP Propagation Tool 
 * ----------------------------------------
 * History 
 * Version : 01/05/2015 : SCA : V2.1
 * Version : 19/07/2022 : LBE : V2.5
 * Redmine 7278: Build gaps in VPlot from sampling
 * ----------------------------------------
 */
package fr.tlse.irap.vplot;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

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

@XmlRootElement
public class SolarSpeedWrapper {

    private List<SolarSpeed> solarSpeeds;
    /**
     * sampling in seconds
     */
    private int sampling = -1;

    public SolarSpeedWrapper() {
        solarSpeeds = new ArrayList<SolarSpeed>();
    }

    public SolarSpeedWrapper(List<SolarSpeed> solarSpeeds) {
        this.solarSpeeds = solarSpeeds;
    }

    @XmlElement
    public List<SolarSpeed> getSolarSpeeds() {
        return solarSpeeds;
    }

    public void setSolarSpeeds(List<SolarSpeed> solarSpeeds) {
        this.solarSpeeds = solarSpeeds;
    }

    /**
     * @return the sampling
     */
    public int getSampling() {
        return sampling;
    }

    /**
     * @param sampling the sampling to set
     */
    public void setSampling(int sampling) {
        this.sampling = sampling;
    }

    public SolarSpeed getNearestFromTime(Calendar calendar) {
        SolarSpeed previous = (solarSpeeds.isEmpty() ? null : solarSpeeds.get(0));
        SolarSpeed next = null;

//        System.out.println("===> Search solar speed ***********");
        for (SolarSpeed solarSpeed : this.solarSpeeds) {
//            System.out.println("===> Compare "+solarSpeed.getEventTime().getTime()+" with "+calendar.getTime()+" speed="+solarSpeed.getSpeed());
            if (solarSpeed.getEventTime().after(calendar) && !Float.isNaN(solarSpeed.getSpeed())) {
//                System.out.println("===> Speed OK! ");
                next = solarSpeed;
                break;
            }
//            System.out.println("===> Go next " + solarSpeed.getSpeed());
            if (!Float.isNaN(solarSpeed.getSpeed())) {
                previous = solarSpeed;
            }
        }

//        System.out.println("===> previous" + previous.getSpeed() +" next="+ next.getSpeed());
        if (next == null) {
            return previous;
        } else {
            Long deltaPrevious = Math.abs(previous.getEventTime().getTimeInMillis() - calendar.getTimeInMillis());
            Long deltaNext = Math.abs(next.getEventTime().getTimeInMillis() - calendar.getTimeInMillis());
            return (deltaPrevious < deltaNext && !Float.isNaN(previous.getSpeed()) ? previous : next);
        }
    }

}
