using Elwig.Documents;
using Elwig.Models.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Elwig.Models.Dtos {
    public class DeliveryAncmtListData : DataTable<DeliveryAncmtListRow> {

        private static readonly (string, string, string?, int?)[] FieldNames = [
            ("Date", "Datum", null, 20),
            ("Branch", "Zweigstelle", null, 30),
            ("MgNr", "MgNr.", null, 12),
            ("Name1", "Name", null, 40),
            ("Name2", "Vorname", null, 40),
            ("DefaultKg", "Ort", null, 40),
            ("SortId", "Sorte", null, 10),
            ("Weight", "Menge", "kg", 20),
            ("CreatedAt", "Angemeldet", null, 35),
            ("ModifiedAt", "Geändert", null, 35),
            ("Status", "Status", null, 20),
        ];

        public DeliveryAncmtListData(IEnumerable<DeliveryAncmtListRow> rows, List<string> filterNames) :
            base(DeliveryAncmtList.Name, DeliveryAncmtList.Name, string.Join(" / ", filterNames), rows, FieldNames) {
        }

        public static async Task<DeliveryAncmtListData> FromQuery(IQueryable<DeliveryAncmt> query, List<string> filterNames) {
            return new((await query
                .Include(a => a.Schedule.Branch)
                .Include(a => a.Member)
                .Include(a => a.Variety)
                .AsSplitQuery()
                .ToListAsync()).Select(d => new DeliveryAncmtListRow(d)), filterNames);
        }
    }

    public class DeliveryAncmtListRow {
        public DateOnly Date;
        public string Branch;
        public int MgNr;
        public string Name1;
        public string? Name2;
        public string AdministrativeName;
        public string? DefaultKg;
        public string SortId;
        public string Variety;
        public DateTime CreatedAt;
        public DateTime? ModifiedAt;
        public int Weight;
        public string? Status;

        public DeliveryAncmtListRow(DeliveryAncmt a) {
            var s = a.Schedule;
            var m = a.Member;

            Date = s.Date;
            Branch = s.Branch.Name;
            MgNr = m.MgNr;
            Name1 = m.AdministrativeName1;
            Name2 = m.AdministrativeName2;
            AdministrativeName = m.AdministrativeName;
            DefaultKg = m.DefaultKg?.Name;
            SortId = a.SortId;
            Variety = a.Variety.Name;
            CreatedAt = a.CreatedAt;
            ModifiedAt = a.ModifiedAt == a.CreatedAt ? null : a.ModifiedAt;
            Weight = a.Weight;
            Status = s.AncmtTo == null ? null : a.CreatedAt >= s.AncmtTo ? "verspät." : "ok";
        }
    }
}
