using System.Collections.Generic;

namespace ViKPI.Internal
{
    internal struct EventItem
    {
        public long T;
        public string Name;
        public string PropsJson;
    }

    internal struct TouchItem
    {
        public long T;
        public byte Phase;
        public float X;
        public float Y;
        public int Finger;
        public string Scene;
    }

    internal struct PerfItem
    {
        public long T;
        public float Fps;
        public float FrameMsP95;
        public float MemMb;
        public float Battery;
        public string Scene;
    }

    internal struct ErrorItem
    {
        public long T;
        public string Type;
        public string Message;
        public string Stack;
        public string Scene;
    }

    /// <summary>
    /// Thread-safe buffer of analytics items for one session, drained into protocol batches.
    /// Errors arrive from log callbacks on any thread; everything else from the main thread.
    /// </summary>
    internal sealed class EventBuffer
    {
        /// <summary>Server limit per batch is 2000 items; stay under with room to spare.</summary>
        public const int MaxItemsPerBatch = 1500;

        /// <summary>A runaway loop calling Track can't grow memory without bound.</summary>
        private const int MaxBuffered = 20000;

        private readonly object _lock = new object();
        private readonly List<EventItem> _events = new List<EventItem>();
        private readonly List<TouchItem> _touches = new List<TouchItem>();
        private readonly List<PerfItem> _perf = new List<PerfItem>();
        private readonly List<ErrorItem> _errors = new List<ErrorItem>();
        private int _dropped;

        public int Count
        {
            get { lock (_lock) return _events.Count + _touches.Count + _perf.Count + _errors.Count; }
        }

        public void Add(EventItem e) { lock (_lock) { if (Room()) _events.Add(e); } }
        public void Add(TouchItem t) { lock (_lock) { if (Room()) _touches.Add(t); } }
        public void Add(PerfItem p) { lock (_lock) { if (Room()) _perf.Add(p); } }
        public void Add(ErrorItem e) { lock (_lock) { if (Room()) _errors.Add(e); } }

        private bool Room()
        {
            if (_events.Count + _touches.Count + _perf.Count + _errors.Count < MaxBuffered) return true;
            if (_dropped++ == 0) Log.Warn("Too many events buffered; dropping until the next upload.");
            return false;
        }

        /// <summary>Moves everything buffered into JSON batch bodies of at most MaxItemsPerBatch items.</summary>
        public List<string> Drain()
        {
            List<EventItem> events; List<TouchItem> touches; List<PerfItem> perf; List<ErrorItem> errors;
            lock (_lock)
            {
                if (_events.Count + _touches.Count + _perf.Count + _errors.Count == 0) return null;
                events = new List<EventItem>(_events); _events.Clear();
                touches = new List<TouchItem>(_touches); _touches.Clear();
                perf = new List<PerfItem>(_perf); _perf.Clear();
                errors = new List<ErrorItem>(_errors); _errors.Clear();
                _dropped = 0;
            }

            var batches = new List<string>();
            int ei = 0, ti = 0, pi = 0, xi = 0;
            while (ei < events.Count || ti < touches.Count || pi < perf.Count || xi < errors.Count)
            {
                var budget = MaxItemsPerBatch;
                var w = new JsonWriter(8192).BeginObject();

                w.Key("events").BeginArray();
                for (; ei < events.Count && budget > 0; ei++, budget--)
                {
                    var e = events[ei];
                    w.BeginObject().Prop("t", e.T).Prop("name", e.Name);
                    if (e.PropsJson != null) w.Key("props").Raw(e.PropsJson);
                    w.EndObject();
                }
                w.EndArray();

                w.Key("errors").BeginArray();
                for (; xi < errors.Count && budget > 0; xi++, budget--)
                {
                    var e = errors[xi];
                    w.BeginObject().Prop("t", e.T).Prop("type", e.Type).Prop("message", e.Message).Prop("stack", e.Stack).Prop("s", e.Scene).EndObject();
                }
                w.EndArray();

                w.Key("perf").BeginArray();
                for (; pi < perf.Count && budget > 0; pi++, budget--)
                {
                    var p = perf[pi];
                    w.BeginObject().Prop("t", p.T).Prop("fps", Round1(p.Fps)).Prop("frameMsP95", Round1(p.FrameMsP95)).Prop("memMb", Round1(p.MemMb));
                    if (p.Battery >= 0) w.Prop("battery", Round1(p.Battery * 100) / 100);
                    w.Prop("s", p.Scene).EndObject();
                }
                w.EndArray();

                w.Key("touches").BeginArray();
                for (; ti < touches.Count && budget > 0; ti++, budget--)
                {
                    var t = touches[ti];
                    w.BeginObject().Prop("t", t.T).Prop("p", t.Phase).Prop("x", Round4(t.X)).Prop("y", Round4(t.Y)).Prop("f", t.Finger).Prop("s", t.Scene).EndObject();
                }
                w.EndArray();

                batches.Add(w.EndObject().ToString());
            }
            return batches;
        }

        private static double Round1(float v) => System.Math.Round(v, 1);
        private static double Round4(float v) => System.Math.Round(v, 4);
    }
}
