using System;
using System.Text.Json.Nodes;

namespace Elwig.Helpers.Weighing {
    /// <summary>
    /// Result of a weighing process on an industrial weighing scale
    /// </summary>
    public struct WeighingResult {
        /// <summary>
        /// Measured gross weight in kg
        /// </summary>
        public int? GrossWeight;

        /// <summary>
        /// Measured tare weight in kg
        /// </summary>
        public int? TareWeight;

        /// <summary>
        /// Measured net weight in kg
        /// </summary>
        public int? NetWeight;

        /// <summary>
        /// Weighing id (or IdentNr) provided by the scale
        /// </summary>
        public string? WeighingId;

        /// <summary>
        /// Wheighing id (or IdentNr) provided by the scale optionally combined with the current date
        /// </summary>
        public string? FullWeighingId;

        /// <summary>
        /// Date string provided by the scale
        /// </summary>
        public DateOnly? Date;

        /// <summary>
        /// Time string provided by the scale
        /// </summary>
        public TimeOnly? Time;

        /// <returns>&lt;[GrossWeight-TaraWeight=]NetWeight/WeighingId/Date/Time&gt;</returns>
        public override readonly string ToString() {
            var w = NetWeight != null ? (GrossWeight != null && TareWeight != null ? $"{GrossWeight}-{TareWeight}=" : "") + $"{NetWeight}kg" : "";
            return $"<{w}/{WeighingId}/{Date:yyyy-MM-dd}/{Time:HH:mm}>";
        }

        public readonly JsonObject ToJson() {
            var obj = new JsonObject();
            if (FullWeighingId != null) obj["id"] = FullWeighingId;
            if (WeighingId != null) obj["nr"] = int.Parse(WeighingId);
            if (Date != null) obj["date"] = $"{Date:yyyy-MM-dd}";
            if (Time != null) obj["time"] = $"{Time:HH:mm:ss}";
            if (GrossWeight != null) obj["gross_weight"] = GrossWeight;
            if (TareWeight != null) obj["tare_weight"] = TareWeight;
            if (NetWeight != null) obj["net_weight"] = NetWeight;
            return obj;
        }
    }
}