package de.frajul.particlelab.entities.particles.attributes.attributeValues;

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

/**
 * Created by Julian on 02.08.2016.
 */
public class Timeline extends ParticleAttributeValue {

    private List<TimelinePoint> points = new ArrayList<>();

    public Timeline() {
        super(ParticleAttributeValueType.TIMELINE);
    }

    public void setValueOfPoint(int index, float value) {
        if (points.size() <= index) {
            points.add(new TimelinePoint());
        }
        points.get(index).setValue(value);
    }

    public void setTimeOfPoint(int index, float time) {
        if (points.size() <= index) {
            points.add(new TimelinePoint());
        }
        points.get(index).setTime(time);
    }

    public float getValueAtTime(float time) {
        TimelinePoint left = null, right = null;
        for (TimelinePoint point : points) {
            if (point.getTime() <= time) {
                if (left == null || left.getTime() < point.getTime())
                    left = point;
            } else if (right == null || right.getTime() > point.getTime())
                right = point;
        }
        if (left != null) {
            if (right != null) {
                float leftDist = 1 - Math.abs(left.getTime() - time);
                float rightDist = 1 - Math.abs(right.getTime() - time);
                float totalDist = leftDist + rightDist;
                return left.getValue() * (leftDist / totalDist) + right.getValue() * (rightDist / totalDist);
            }
            return left.getValue();
        }
        return 0;
    }

}