package de.frajul.endlessroll.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 = Math.abs(left.getTime() - time);
                float rightDist = Math.abs(right.getTime() - time);
                float totalDist = leftDist + rightDist;
                float leftMultiplier = 1 - (leftDist / totalDist);
                float rightMultiplier = 1 - (rightDist / totalDist);
                return left.getValue() * leftMultiplier + right.getValue() * rightMultiplier;
            }
            return left.getValue();
        }
        return 0;
    }

}