using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace MainShell.Converter
{
    public class BoolToVisibleConverter : IValueConverter
    {
        // 将 bool (或可转换为 bool 的值) 转换为 Visibility
        // parameter 支持：
        //   包含 "invert" / "inverse" / "not" / "!" 的字符串 — 反转布尔值
        //   包含 "hidden" 的字符串 — 当为 false 时返回 Visibility.Hidden 而不是 Collapsed
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isVisible = false;

            if (value is bool b)
            {
                isVisible = b;
            }
            else if (value is bool?)
            {
                isVisible = ((bool?)value) ?? false;
            }
            else if (value is string s)
            {
                bool.TryParse(s, out isVisible);
            }
            else if (value != null)
            {
                try
                {
                    isVisible = System.Convert.ToBoolean(value);
                }
                catch
                {
                    isVisible = false;
                }
            }

            var paramString = parameter as string;
            bool invert = false;
            bool useHidden = false;
            if (!string.IsNullOrEmpty(paramString))
            {
                var p = paramString.ToLowerInvariant();
                if (p.Contains("invert") || p.Contains("inverse") || p.Contains("not") || p.Contains("!"))
                    invert = true;
                if (p.Contains("hidden"))
                    useHidden = true;
            }

            if (invert)
                isVisible = !isVisible;

            return isVisible ? Visibility.Visible : (useHidden ? Visibility.Hidden : Visibility.Collapsed);
        }

        // 将 Visibility 转换回 bool
        // Visible => true；Hidden/Collapsed => false
        // 支持与 Convert 相同的 parameter 反转语义
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is Visibility))
                return Binding.DoNothing;

            var vis = (Visibility)value;
            bool result = vis == Visibility.Visible;

            var paramString = parameter as string;
            if (!string.IsNullOrEmpty(paramString))
            {
                var p = paramString.ToLowerInvariant();
                if (p.Contains("invert") || p.Contains("inverse") || p.Contains("not") || p.Contains("!"))
                    result = !result;
            }

            if (targetType == typeof(bool) || targetType == typeof(object))
                return result;
            if (targetType == typeof(bool?))
                return (bool?)result;

            try
            {
                return System.Convert.ChangeType(result, targetType);
            }
            catch
            {
                return result;
            }
        }
    }
}
