using System;
using System.Linq;
using Syncfusion.Data.Extensions;
using Syncfusion.SfDataGrid.XForms;
using Xamarin.Forms;

namespace InABox.Mobile
{

    public class MobileGridNumericConverter : AbstractConverter<double, object>
    {
        protected override object Convert(double value, object? parameter = null)
        {
            return value;
        }
    }
    
    public abstract class MobileGridNumericColumn<TEntity, TType> : MobileGridColumn<TEntity, TType>
        where TType : struct, IComparable, IComparable<TType>, IConvertible, IEquatable<TType>, IFormattable
    {
        public MobileGridSummaryType Summary { get; set; }
        
        public bool BlankIfZero { get; set; }
        
        public String Format { get; set; }
        
        public MobileGridNumericColumn() : base()
        {
            Width = GridLength.Auto;
            BlankIfZero = true;
        }

        private bool IsIntegral()
        {
            return new Type[] 
                { 
                    typeof(sbyte), typeof(SByte), 
                    typeof(byte), typeof(Byte), 
                    typeof(short), typeof(Int16), 
                    typeof(ushort), typeof(UInt16), 
                    typeof(int), typeof(Int32), 
                    typeof(uint), typeof(UInt32), 
                    typeof(long), typeof(Int64), 
                    typeof(ulong), typeof(UInt64)
                }
                .Contains(typeof(TType));
        }
        
        public GridSummaryColumn CreateSummaryColumn()
        {
            if (Summary == MobileGridSummaryType.None)
                return null;
            var result = new GridSummaryColumn();
            result.SummaryType = IsIntegral()
                ? Syncfusion.Data.SummaryType.Int32Aggregate
                : Syncfusion.Data.SummaryType.DoubleAggregate;
            result.Format = Summary == MobileGridSummaryType.Count
                ? "{}{Count}"
                : "{}{Sum}";
            result.MappingName = ColumnName;
            return result;
        }

        protected override object FormatValue(object value)
        {
            if (BlankIfZero && Equals(value, default(TType)))
                return "";
            return String.IsNullOrWhiteSpace(Format)
                ? value.ToString()
                : String.Format($"{{0:{Format}}}", value);
        }
    }
}