using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TELTest.Gamemodes;

namespace TELTest {
    internal static class QuizDraftManager {
        static QuizDraftManager() {
            tmr.Interval = 15000;
            tmr.Elapsed += Tmr_Elapsed;
            tmr.AutoReset = false;
            //LoadAll();
            
        }
        static BasicKeyValue bk = new BasicKeyValue("Drafts1");
        private static void Tmr_Elapsed(Object sender, System.Timers.ElapsedEventArgs e) {
            Program.WriteWithTime("Begin write drafts...");
            bk.SavePendingChanges();
            Program.WriteWithTime("Done. {0} tuples out, ~{1}B memory in use.", bk.LastTuplesOut, bk.CurrentMemoryPressure);
        }
            //DumpAllDrafts();

        public static bool Contains(string id) {
            return bk.ContainsKey(id);
        }
        private static void Retime() {
            tmr.Stop();
            tmr.Start();
        }
        public static string SaveNewDraft(QuizContainer container) {
            string id = null;
            while (true) {
                id = Utilities.RandomString(15);
                if (bk.ContainsKey(id)) continue;
                var bytes = System.Text.Encoding.UTF8.GetBytes(container.SerializeXML());
                lock (bk) bk[id] = bytes;
                break;
            }
            Retime();
            return id;
        }
        public static bool SaveDraft(QuizContainer container, string id) {
            //lock (AllDrafts) {
            //    if (!AllDrafts.ContainsKey(id)) return false;
            //    AllDrafts[id] = container;
            //}
            bk[id] = System.Text.Encoding.UTF8.GetBytes(container.SerializeXML());
            Retime();
            return true;
        }
        public static bool DeleteDraft(string id) {
            //lock (AllDrafts) {
                bk.Remove(id);
                Retime();
                //return AllDrafts.Remove(id);

                return true;
            //}
        }
        public static QuizContainer GetDraft(string id) {
            if (bk.ContainsKey(id)) {
                byte[] sr = bk[id];
                QuizContainer qc = QuizContainer.FromXml(System.Text.Encoding.UTF8.GetString(sr));
                return qc;
            }
            return null;
            //lock (AllDrafts) {
            //    if (AllDrafts.ContainsKey(id)) return AllDrafts[id];
            //}
            //return null;
        }
        private static object _dmpLock = new object();
        static System.Timers.Timer tmr = new System.Timers.Timer();
       
    }
}
