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

namespace InABox.Mobile
{
    internal class MobileGridDateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is DateTime date)
                return date.IsEmpty() && BlankIfZero
                    ?  "" 
                    : date.ToString(Format);
            return "";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
        
        public String Format { get; set; }
        public bool BlankIfZero { get; set; }
        
    }

    public class MobileGridDateColumn<TEntity> : MobileGridColumn<TEntity, DateTime>
    {

        public String Format { get; set; }

        public bool BlankIfZero { get; set; }

        public MobileGridDateColumn() : base()
        {
            Width = GridLength.Auto;
            Format = @"dd MMM yy";
            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 MobileGridDateConverter()
                {
                    Format = this.Format,
                    BlankIfZero = this.BlankIfZero
                });
            return result;
        }

    }

}