using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;

public class MeshLoadingBar : UdonSharpBehaviour
{
    private Renderer targetRenderer;
    private MaterialPropertyBlock propertyBlock;

    private float progress;

    private Color BACKGROUND_COLOR = Color.black;

    private Color color = Color.white;
    private Color backgroundColor = Color.black;

    void Start()
    {
        targetRenderer = GetComponent<MeshRenderer>();
        backgroundColor = BACKGROUND_COLOR;
        color = BACKGROUND_COLOR;
        propertyBlock = new MaterialPropertyBlock();
        ApplyProperties();
    }

    public void SetColor(Color newColor)
    {
        color = newColor;
        backgroundColor = newColor;
        ApplyProperties();
    }

    public void SetLoadingColor(Color loadingColor)
    {
        color = loadingColor;
        backgroundColor = BACKGROUND_COLOR;
        ApplyProperties();
    }

    public void SetProgress(float newProgress)
    {
        progress = Mathf.Clamp01(newProgress);
        ApplyProperties();
    }

    private void ApplyProperties()
    {
        if (targetRenderer == null) return;

        targetRenderer.GetPropertyBlock(propertyBlock);

        propertyBlock.SetFloat("_Progress", progress);
        propertyBlock.SetColor("_Color", color);
        propertyBlock.SetColor("_BackgroundColor", backgroundColor);
        targetRenderer.SetPropertyBlock(propertyBlock);
    }
}