using CounterDrone.Core.Algorithms;
using System;
using System.Collections.Generic;
using System.Text.Json;

namespace CounterDrone.Core.Simulation
{
    public class ControlZoneEntity
    {
        public string Id { get; }
        public string Name { get; }
        public List<Vector3> Vertices { get; }
        public float MinAltitude { get; }
        public float MaxAltitude { get; }

        /// <summary>预缓存的水平投影顶点 (X,Z)，ContainsPoint 每帧高频调用时避免重复分配数组</summary>
        private readonly (float X, float Z)[] _vertices2D;

        public struct Vector3 { public float X { get; set; } public float Y { get; set; } public float Z { get; set; } }

        public ControlZoneEntity(string id, string name, string verticesJson, float minAlt, float maxAlt)
        {
            Id = id;
            Name = name;
            MinAltitude = minAlt;
            MaxAltitude = maxAlt;
            Vertices = JsonSerializer.Deserialize<List<Vector3>>(verticesJson) ?? new();
            _vertices2D = new (float X, float Z)[Vertices.Count];
            for (int i = 0; i < Vertices.Count; i++)
                _vertices2D[i] = (Vertices[i].X, Vertices[i].Z);
        }

        public bool ContainsPoint(float x, float y, float z)
        {
            if (y < MinAltitude || y > MaxAltitude) return false;
            return Kinematics.PointInPolygon(x, z, _vertices2D);
        }
    }
}
