using isnd.Data.Packages;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace isnd.Data.Catalog
{
    public class RegistrationPageIndex : HappyIdOwner
    {

        public RegistrationPageIndex(string url) : base(url)
        {
            Items = new List<RegistrationPage>();
        }

        public RegistrationPageIndex(string bid, string id, string extUrl, IEnumerable<Package> pkgs) : base(bid + $"/{id}/index.json")
        {
            Items = new List<RegistrationPage>();
            long cnid = 0;
            var pkgsGroups = pkgs.GroupBy(l => l.Id);
            // Pour tous les groupes par Id
            foreach (var gsp in pkgsGroups)
            {
                var pkgsbi = gsp.ToArray();
                List<PackageVersion> versions = new List<PackageVersion>();

                foreach(var l in pkgsbi.Select(p => p.Versions))
                {
                    versions.AddRange(l);
                    foreach (var pv in l)
                    {
                        if (pv.CommitNId> cnid)
                        {
                            cnid = pv.CommitNId;
                        }
                    }
                }
                Items.Add(new RegistrationPage(bid, gsp.Key, extUrl, versions));
            }
            CommitId = cnid.ToString();
        }

        [JsonProperty("count")]
        public int Count { get => Items.Count; }

        [JsonProperty("items")]
        public List<RegistrationPage> Items { get; set; }

        public string CommitId { get; set; }
        public DateTime CommitTimeStamp { get; internal set; }
    }
}