using System;
using System.Globalization;
using Syncfusion.SfDataGrid.XForms;
using Xamarin.Forms;

namespace InABox.Mobile
{
    
    internal class MobileGridTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is TimeSpan time)
                return time.Equals(TimeSpan.Zero) 
                    ? "" 
                    : time.ToString(Format);
            return "";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        
        public String Format { get; set; }
        public bool BlankIfZero { get; set; }
        
    }
    
    public class MobileGridTimeColumn<TEntity> : MobileGridColumn<TEntity, TimeSpan>
    {
        
        public String Format { get; set; }
        
        public bool BlankIfZero { get; set; }
        
        public MobileGridTimeColumn() : base()
        {
            Width = GridLength.Auto;
            Format = @"h\:mm";
            Alignment = TextAlignment.Center;
            BlankIfZero = true;
        }
        
        public override GridColumn CreateColumn()
        {
            var result = CreateColumn<GridTextColumn>();
            result.Format = Format;
            result.DisplayBinding = new Binding(
                this.ColumnName, 
                BindingMode.Default, 
                new MobileGridTimeConverter()
                {
                    Format = this.Format, 
                    BlankIfZero =  this.BlankIfZero
                });
            return result;
        }
    }
}