using CommunityToolkit.Mvvm.ComponentModel;

namespace ConeCalorimeter.ViewModels;

public sealed class ReportFieldViewModel : ObservableObject
{
    private string _value;
    private bool _isAutoFilled;
    private bool _isSettingAutoValue;

    public ReportFieldViewModel(string key, string label, string value = "")
    {
        Key = key;
        Label = label;
        _value = value;
    }

    public string Key { get; }

    public string Label { get; }

    public bool IsAutoFilled
    {
        get => _isAutoFilled;
        private set => SetProperty(ref _isAutoFilled, value);
    }

    public string Value
    {
        get => _value;
        set
        {
            if (SetProperty(ref _value, value) && !_isSettingAutoValue)
            {
                IsAutoFilled = false;
            }
        }
    }

    public void SetAutoValue(string value, bool overwriteManual = false)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return;
        }

        if (!overwriteManual && !string.IsNullOrWhiteSpace(Value) && !_isAutoFilled)
        {
            return;
        }

        _isSettingAutoValue = true;
        Value = value;
        _isSettingAutoValue = false;
        IsAutoFilled = true;
    }

    public void SetPersistedValue(string value, bool isAutoFilled)
    {
        _isSettingAutoValue = true;
        Value = value;
        _isSettingAutoValue = false;
        IsAutoFilled = isAutoFilled;
    }
}
