using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 字节大小类型
    /// </summary>
    public enum ByteSizeType
    {
        B = 0,
        KB = 1,
        MB = 2,
        GB = 3
    }

    /// <summary>
    /// 字节大小转化器
    /// </summary>
    public class ByteSizeConverter : IValueConverter
    {
        /// <summary>
        /// 输入类型
        /// </summary>
        public ByteSizeType InType { get; set; } = ByteSizeType.B;

        /// <summary>
        /// 输出类型
        /// </summary>
        public ByteSizeType OutType { get; set; } = ByteSizeType.B;

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return 0d;

            if (!double.TryParse(value.ToString(), out double v))
            {
                return 0d;
            }

            int _in = (int)this.InType;
            int _out = (int)this.OutType;

            while (_in != _out)
            {
                if (_in < _out)
                {
                    v /= 1024f;
                    ++_in;
                }
                else
                {
                    v *= 1024f;
                    --_in;
                }
            }

            return v;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return 0d;

            if (!double.TryParse(value.ToString(), out double v))
            {
                return 0d;
            }

            int _in = (int)this.OutType;
            int _out = (int)this.InType;

            while (_in != _out)
            {
                if (_in < _out)
                {
                    v /= 1024f;
                    ++_in;
                }
                else
                {
                    v *= 1024f;
                    --_in;
                }
            }

            return v;
        }
    }
}
