using System;
using ImageProcessing.Core;
using Prism.Mvvm;

namespace XplorePlane.ViewModels
{
    public class ProcessorParameterVM : BindableBase
    {
        private object _value;
        private bool _isValueValid = true;

        public ProcessorParameterVM(ProcessorParameter parameter)
        {
            Name = parameter.Name;
            DisplayName = parameter.DisplayName;
            _value = parameter.Value;
            MinValue = parameter.MinValue;
            MaxValue = parameter.MaxValue;
            ParameterType = parameter.ValueType?.Name?.ToLower() switch
            {
                "int32" or "int" => "int",
                "double" => "double",
                "boolean" or "bool" => "bool",
                _ => "enum"
            };
            ValidateValue(_value);
        }

        public string Name { get; }
        public string DisplayName { get; }
        public object MinValue { get; }
        public object MaxValue { get; }
        public string ParameterType { get; }

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

        public object Value
        {
            get => _value;
            set
            {
                if (SetProperty(ref _value, value))
                    ValidateValue(value);
            }
        }

        private void ValidateValue(object value)
        {
            if (value == null || MinValue == null || MaxValue == null)
            {
                IsValueValid = true;
                return;
            }
            try
            {
                double dVal = Convert.ToDouble(value);
                double dMin = Convert.ToDouble(MinValue);
                double dMax = Convert.ToDouble(MaxValue);
                IsValueValid = dVal >= dMin && dVal <= dMax;
            }
            catch
            {
                IsValueValid = true; // 非数值类型不做范围校验
            }
        }
    }
}
