using System.Data;
using System.Runtime.CompilerServices;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

namespace demos;

class ValueConversions
{
    public static async Task Demo()
    {
        using var db = new MyContext();

        await db.PrepareDatabase();

        await db.AddAsync(new VC() { Duration = new Duration(1, 30) });
        await db.SaveChangesAsync();
        await db.Set<VC>().Where(x => x.Duration == new Duration(1, 30)).LoadAsync();
    }

    class MyContext : MyDbContextBase
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<VC>(b =>
            {
                b.Property(x => x.Duration).HasConversion(new DurationConverter());
            });
            //new EnumToStringConverter
        }
    }

    class VC
    {
        public int Id { get; set; }
        public Duration Duration { get; set; }
    }

    class Duration(int hours, int minutes)
    {
        public int Hours { get; set; } = hours;
        public int Minutes { get; set; } = minutes;
    }

    class DurationConverter : ValueConverter<Duration, int>
    {
        public DurationConverter()
            : base(d => d.Hours * 60 + d.Minutes, x => new Duration(x / 60, x % 60))
        { }
    }
}
