﻿using UdonSharp;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.UI;
using VRC.SDK3.Persistence;
using VRC.SDKBase;

public class UdonPostProcessing : UdonSharpBehaviour
{
    [SerializeField] private Slider _weightSlider;
    [SerializeField] private PostProcessVolume _volume;
    
    private const string PP_WEIGHT_KEY = "settings_pp_weight";
    private float _appliedValue;

    public void SliderUpdated()
    {
        PlayerData.SetFloat(PP_WEIGHT_KEY, _weightSlider.value);
    }

    public override void OnPlayerDataUpdated(VRCPlayerApi player, PlayerData.Info[] infos)
    {
        if (player != Networking.LocalPlayer) return; // only update for local
        if (!PlayerData.HasKey(player, PP_WEIGHT_KEY)) return; // only update if the key exists
        if (PlayerData.GetType(player, PP_WEIGHT_KEY) != typeof(float)) return; // only update if the key has the right type
        
        SetWeight(PlayerData.GetFloat(player, PP_WEIGHT_KEY)); // update
    }

    private void SetWeight(float bloomValue)
    {
        if (Mathf.Approximately(_appliedValue, bloomValue)) return; // don't update if it's already the same
        _appliedValue = bloomValue;
        _volume.weight = bloomValue;
        _weightSlider.value = bloomValue;
    }
}
