using System;
using Godot;
using static ld48.Extensions;

public class PixelCamera : Camera2D {
    private Vector2 Resolution = V2(1024f, 768f);
    private Viewport viewport;
    private float scaleFactor = 1f;

    private ColorRect postShader;
    private ColorRect fade;

    private float EPSILON = 0.001f;

    public static Color fadeColor = Colors.Transparent;

    public override void _Ready() {
        viewport = GetViewport();
        viewport.Connect("size_changed", this, "ViewportSizeChanged");

        postShader = GetParent().GetNode("Over").GetNode<ColorRect>("Post");
        fade = GetParent().GetNode("UI").GetNode<ColorRect>("Fade");
        
        ViewportSizeChanged();
    }

    public override void _Process(float delta) {
        base._Process(delta);

        fade.Color = fadeColor;
        (postShader.Material as ShaderMaterial).SetShaderParam("cameraPosition", GetCameraPosition());
    }

    private void ViewportSizeChanged() {
        // var scaleV = viewport.Size / Resolution;
        // var new_scaling_factor = Mathf.Max(Mathf.Floor(Mathf.Min(scaleV[0], scaleV[1])), 1);
        // if (Math.Abs(new_scaling_factor - scaleFactor) > EPSILON) {
            // scaleFactor = new_scaling_factor;
            // Zoom = V2(1 / scaleFactor, 1 / scaleFactor);
        // }

        postShader.RectSize = viewport.Size;
        fade.RectSize = viewport.Size;
        (postShader.Material as ShaderMaterial).SetShaderParam("viewportSize", viewport.Size);
    }
}
