using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace ViKPI.Internal
{
    /// <summary>
    /// Minimal allocation-light JSON writer for the ingest protocol. JsonUtility can't write
    /// dictionaries, and pulling in a JSON library would force a dependency on every game.
    /// </summary>
    internal sealed class JsonWriter
    {
        private readonly StringBuilder _sb;
        private bool _needComma;

        public JsonWriter(int capacity = 256) => _sb = new StringBuilder(capacity);

        public int Length => _sb.Length;

        public JsonWriter BeginObject() { Sep(); _sb.Append('{'); _needComma = false; return this; }
        public JsonWriter EndObject() { _sb.Append('}'); _needComma = true; return this; }
        public JsonWriter BeginArray() { Sep(); _sb.Append('['); _needComma = false; return this; }
        public JsonWriter EndArray() { _sb.Append(']'); _needComma = true; return this; }

        public JsonWriter Key(string key)
        {
            Sep();
            WriteString(key);
            _sb.Append(':');
            _needComma = false;
            return this;
        }

        public JsonWriter Value(string value)
        {
            Sep();
            if (value == null) _sb.Append("null");
            else WriteString(value);
            _needComma = true;
            return this;
        }

        public JsonWriter Value(long value) { Sep(); _sb.Append(value.ToString(CultureInfo.InvariantCulture)); _needComma = true; return this; }

        public JsonWriter Value(double value)
        {
            Sep();
            // JSON has no NaN or Infinity; the server would reject the whole batch.
            if (double.IsNaN(value) || double.IsInfinity(value)) _sb.Append('0');
            else _sb.Append(value.ToString("R", CultureInfo.InvariantCulture));
            _needComma = true;
            return this;
        }

        public JsonWriter Value(bool value) { Sep(); _sb.Append(value ? "true" : "false"); _needComma = true; return this; }

        /// <summary>Inserts pre-serialized JSON, e.g. event props built once at Track time.</summary>
        public JsonWriter Raw(string json) { Sep(); _sb.Append(json); _needComma = true; return this; }

        public JsonWriter Prop(string key, string value) => Key(key).Value(value);
        public JsonWriter Prop(string key, long value) => Key(key).Value(value);
        public JsonWriter Prop(string key, double value) => Key(key).Value(value);
        public JsonWriter Prop(string key, bool value) => Key(key).Value(value);

        public override string ToString() => _sb.ToString();

        private void Sep()
        {
            if (_needComma) _sb.Append(',');
        }

        private void WriteString(string s)
        {
            _sb.Append('"');
            foreach (var c in s)
            {
                switch (c)
                {
                    case '"': _sb.Append("\\\""); break;
                    case '\\': _sb.Append("\\\\"); break;
                    case '\n': _sb.Append("\\n"); break;
                    case '\r': _sb.Append("\\r"); break;
                    case '\t': _sb.Append("\\t"); break;
                    default:
                        if (c < 0x20) _sb.Append("\\u").Append(((int)c).ToString("x4"));
                        else _sb.Append(c);
                        break;
                }
            }
            _sb.Append('"');
        }

        /// <summary>
        /// Serializes event properties under the protocol's limits: string, number and bool values;
        /// anything else becomes its string form. Returns null when there is nothing to send.
        /// </summary>
        /// <summary>float to double without the binary noise: 0.1f writes as 0.1, not 0.100000001490116.</summary>
        private static double Widen(float f) =>
            double.TryParse(f.ToString("R", CultureInfo.InvariantCulture), NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : 0;

        public static string Props(IDictionary<string, object> props)
        {
            if (props == null || props.Count == 0) return null;
            var w = new JsonWriter(64 + props.Count * 24).BeginObject();
            var n = 0;
            foreach (var kv in props)
            {
                if (n >= EventValidator.MaxProps) break;
                if (string.IsNullOrWhiteSpace(kv.Key)) continue;
                w.Key(DeviceInfo.Clip(kv.Key.Trim(), EventValidator.MaxPropKeyLength));
                switch (kv.Value)
                {
                    case null: w.Value(""); break;
                    case string s: w.Value(DeviceInfo.Clip(s, EventValidator.MaxPropValueLength)); break;
                    case bool b: w.Value(b); break;
                    case int i: w.Value(i); break;
                    case long l: w.Value(l); break;
                    case short sh: w.Value(sh); break;
                    case byte by: w.Value(by); break;
                    case uint ui: w.Value(ui); break;
                    case float f: w.Value(Widen(f)); break;
                    case double d: w.Value(d); break;
                    case decimal m: w.Value((double)m); break;
                    case Enum e: w.Value(e.ToString()); break;
                    case IFormattable fmt: w.Value(DeviceInfo.Clip(fmt.ToString(null, CultureInfo.InvariantCulture), EventValidator.MaxPropValueLength)); break;
                    default: w.Value(DeviceInfo.Clip(kv.Value.ToString(), EventValidator.MaxPropValueLength)); break;
                }
                n++;
            }
            return n == 0 ? null : w.EndObject().ToString();
        }
    }
}
