using System.Collections.Generic;
using System.Text.Json.Nodes;

namespace Elwig.Helpers.Billing {
    public class GraphEntry {

        public int Id { get; set; }
        public BillingData.CurveMode Mode { get; set; }
        public Graph DataGraph { get; set; }
        public Graph? GebundenGraph { get; set; }
        public decimal? GebundenFlatPrice { get; set; }
        public List<string> Contracts { get; set; }
        private int MinX { get; set; }
        private int MaxX { get; set; }

        public GraphEntry(int id, BillingData.CurveMode mode, int minX, int maxX) {
            Id = id;
            Mode = mode;
            MinX = minX;
            MaxX = maxX;
            DataGraph = new Graph(minX, maxX);
            Contracts = [];
        }

        public GraphEntry(int id, BillingData.CurveMode mode, Dictionary<double, decimal> data, int minX, int maxX) :
            this(id, mode, minX, maxX) {
            DataGraph = new Graph(data, minX, maxX);
        }

        public GraphEntry(int id, BillingData.Curve curve, int minX, int maxX) :
            this(id, curve.Mode, minX, maxX) {
            DataGraph = new Graph(curve.Normal, minX, maxX);
            if (curve.Gebunden != null)
                GebundenGraph = new Graph(curve.Gebunden, minX, maxX);
        }

        private GraphEntry(int id, BillingData.CurveMode mode, Graph dataGraph, Graph? gebundenGraph,
                           decimal? gebundenFlatPrice, List<string> contracts, int minX, int maxX) {
            Id = id;
            Mode = mode;
            MinX = minX;
            MaxX = maxX;
            DataGraph = dataGraph;
            GebundenGraph = gebundenGraph;
            GebundenFlatPrice = gebundenFlatPrice;
            Contracts = contracts;
        }

        public JsonObject ToJson() {
            var curve = new JsonObject {
                ["id"] = Id,
                ["mode"] = Mode.ToString().ToLower(),
            };

            curve["data"] = DataGraph.ToJson(Mode.ToString().ToLower());

            if (GebundenFlatPrice != null) {
                curve["geb"] = GebundenFlatPrice.ToString();
            } else if (GebundenGraph != null) {
                curve["geb"] = GebundenGraph.ToJson(Mode.ToString().ToLower());
            }

            return curve;
        }

        public GraphEntry Copy(int id) {
            return new GraphEntry(id, Mode, (Graph)DataGraph.Clone(), (Graph?)GebundenGraph?.Clone(), GebundenFlatPrice, Contracts, MinX, MaxX);
        }
    }
}