using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TELTest.Matchmaking;

namespace TELTest {
    public static class MatchmakingStuff {
        static MatchmakingStuff() {
            tmr.Interval = 60 * 60_000; // Every hour
            tmr.Elapsed += Tmr_Elapsed;
            tmr.AutoReset = true;
            Retime();

        }
        static System.Timers.Timer tmr = new System.Timers.Timer();
        private static void Tmr_Elapsed(Object sender, System.Timers.ElapsedEventArgs e) {
            Program.WriteWithTime("Begin lobby cleanup...");
            RunCleanup();
        }
        private static void Retime() {
            tmr.Stop();
            tmr.Start();
        }
        public static Lobby RequestNew(QuizContainer subject, QuizGamemode gamemode) {
            Lobby m = new Lobby();
            m.Subject = subject;
            m.Gamemode = gamemode;
            m.Identifier = Utilities.RandomString(5);
            m.LastAccessed = DateTime.Now;
            lock (AllLobbies)
                AllLobbies.Add(m);
            return m;
        }
        public static List<Lobby> GetPublic() {
            lock(AllLobbies)
                return AllLobbies.Where(x => x.AnnouncePublic).ToList();
        }
        public static void RunCleanup() {
            List<Lobby> remove = new List<Lobby>();
            lock (AllLobbies)
                for (Int32 i = 0; i < AllLobbies.Count; i++) {
                    Lobby item = AllLobbies[i];
                    if (item.Players.Count == 0 || DateTime.Now - item.LastAccessed > new TimeSpan(2, 0, 0) && !item.AnnouncePublic) remove.Add(item);
                }
            lock(AllLobbies)
                foreach (var item in remove) AllLobbies.Remove(item);
        }

        public static List<Lobby> AllLobbies { get; } = new List<Lobby>();
    }
}
