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

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

import de.frajul.particlelab.data.Color;
import de.frajul.particlelab.main.GameLog;

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

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

    public TintTimeline() {
        super(ParticleAttributeValueType.TINT_TIMELINE);
    }

    public void setValueOfPoint(int index, int colorIndex, float value) {
        GameLog.i("Set value: index="+index+"; colorIndex="+colorIndex+"; value="+value);
        if (points.size() <= index) {
            points.add(new TintTimelinePoint());
        }
        points.get(index).setValue(colorIndex, value);
    }

    public void setTimeOfPoint(int index, float time) {
        GameLog.i("Set time: index="+index+"; time="+time);
        if (points.size() <= index) {
            points.add(new TintTimelinePoint());
        }
        points.get(index).setTime(time);
    }

    public Color getValueAtTime(float time) {
        TintTimelinePoint left = null, right = null;
        for (TintTimelinePoint 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.getColor().mix((leftDist / totalDist), (rightDist / totalDist), right.getColor());
            }
            return left.getColor();
        }
        return new Color();
    }

}
