using SWRIS.Enums;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO.Ports;
using System.Windows.Data;
using System.Windows.Media;

namespace SWRIS.Converters
{
    public class LimitStateToColorConverter : IValueConverter
    {
        private static readonly Dictionary<string, SolidColorBrush> _brushCache = new Dictionary<string, SolidColorBrush>();
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is LimitState limit)
            {
                double opacity = parameter != null ? System.Convert.ToDouble(parameter) : 1;
                string cacheKey = $"{limit}_{opacity}";
                // 如果缓存中存在，直接返回
                if (_brushCache.TryGetValue(cacheKey, out var cachedBrush))
                {
                    return cachedBrush;
                }
                SolidColorBrush colorBrush;
                switch (limit)
                {
                    case LimitState.Offline:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#7886B2"));
                        break;
                    case LimitState.NotInLimit:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00FF78"));
                        break;
                    case LimitState.AtLimit:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF0000"));
                        break;
                    default:
                        colorBrush = Brushes.Transparent;
                        break;
                }
                colorBrush.Opacity = opacity;
                colorBrush.Freeze();
                _brushCache[cacheKey] = colorBrush;
                return colorBrush;
            }
            return Brushes.Transparent;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value is bool b ? !b : value;
        }
    }
}
