package com.lemenzo.clock.bedtime;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.view.View;

public final class SunriseView extends View {
    private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private float progress;

    private static final int[] STOPS = {
            Color.rgb(0, 0, 0),
            Color.rgb(3, 8, 20),
            Color.rgb(13, 35, 74),
            Color.rgb(47, 129, 247),
            Color.rgb(88, 54, 146),
            Color.rgb(222, 107, 67),
            Color.rgb(255, 205, 150)
    };

    public SunriseView(Context context) {
        super(context);
        setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
    }

    public void setProgress(float value) {
        progress = Math.max(0f, Math.min(1f, value));
        invalidate();
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int top = blend(STOPS, Math.min(1f, progress * 1.18f));
        int bottom = blend(STOPS, Math.max(0f, progress - .12f));
        paint.setShader(new LinearGradient(0, 0, 0, getHeight(), top, bottom, Shader.TileMode.CLAMP));
        canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
    }

    static int blend(int[] colors, float p) {
        if (p <= 0f) return colors[0];
        if (p >= 1f) return colors[colors.length - 1];
        float scaled = p * (colors.length - 1);
        int i = Math.min(colors.length - 2, (int) scaled);
        float local = scaled - i;
        return Color.rgb(
                Math.round(Color.red(colors[i]) + (Color.red(colors[i + 1]) - Color.red(colors[i])) * local),
                Math.round(Color.green(colors[i]) + (Color.green(colors[i + 1]) - Color.green(colors[i])) * local),
                Math.round(Color.blue(colors[i]) + (Color.blue(colors[i + 1]) - Color.blue(colors[i])) * local));
    }
}
