package me.koba1.led.model.colors;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import me.koba1.led.utils.gradient.ClaudeOklchGradientUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Getter
@ToString
public class KobaGradient {

    public record GradientStop(int id, double position, KobaColor color) {}

    private final List<GradientStop> stops;

    @JsonIgnore private KobaColor[] colorCache;

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public KobaGradient(List<GradientStop> gradientStops) {
        this.stops = (gradientStops != null ? new ArrayList<>(gradientStops) : new ArrayList<GradientStop>())
                .stream()
                .map(stop -> new GradientStop(stop.id(), stop.position() / 100.0, stop.color()))
                .sorted(Comparator.comparingDouble(GradientStop::position))
                .collect(Collectors.toList());
    }

    public KobaGradient() {
        this(Arrays.asList(
                new GradientStop(0, 0, new KobaColor("#00FF00")),
                new GradientStop(1, 100, new KobaColor("#0000FF")) // ITT AZÉRT SZÁZ MERT VISSZAOSZTOM FENT!
        ));
    }

    public KobaColor getColor(int ledIndex, int ledCount) {
        if(colorCache == null || colorCache.length != ledCount) {
            colorCache = ClaudeOklchGradientUtils.bakeGradient(this, ledCount);
             System.out.println("Rebuilding color cache");
        }

        return colorCache[ledIndex];
    }

    @JsonValue
    public List<GradientStop> getStopsForJson() { // Hogy rögtön a gradient legyen a stop, ne legyen stops key is
        return stops;
    }
}