using LibS7Adv;
using System.Windows;
using System.Windows.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Diagnostics;
using CtrEditor.FuncionesBase;
using System.ComponentModel;

namespace CtrEditor.ObjetosSim
{
    /// <summary>
    /// Interaction logic for ucBottGenerator.xaml
    /// </summary>
    public partial class osBottGenerator : osBase, IosBase
    {
        TimerTON_TOFF _TON_TOFF = new TimerTON_TOFF();
        private float TiempoRestante;
        public static string NombreClase()
        {
            return "BottGenerator";
        }

        private string nombre = NombreClase();
        public override string Nombre { get => nombre; set => SetProperty(ref nombre, value); }

        [ObservableProperty]
        private float offsetLeftSalida;
        [ObservableProperty]
        private float offsetTopSalida;
        [ObservableProperty]
        [property: Description("The bottle will be destroyed if fall outside transport.")]
        [property: Category("Enable to Run:")]
        private bool preserve_Outside_Transport;
        [ObservableProperty]
        [property: Description("PLC tag for consense to run. 1 => always")]
        [property: Category("Enable to Run:")]
        private string tag_consenso;
        [ObservableProperty]
        [property: Description("Consense to run.")]
        [property: Category("Enable to Run:")]
        private bool consenso;
        partial void OnConsensoChanged(bool value)
        {
            _TON_TOFF.Senal = value;
        }

        [ObservableProperty]
        [property: Description("Consense is Normally close.")]
        [property: Category("Enable to Run:")]
        private bool consenso_NC;
        [ObservableProperty]
        [property: Description("Enable filter.")]
        [property: Category("Enable to Run:")]
        private bool consenso_Filtrado;
        [ObservableProperty]
        [property: Description("Time ON in s.")]
        [property: Category("Enable to Run:")]
        float filtro_consenso_ON_s;
        [ObservableProperty]
        [property: Description("Time OFF in s.")]
        [property: Category("Enable to Run:")]
        float filtro_consenso_OFF_s;
        [ObservableProperty]
        [property: Description("Filter OUT signal.")]
        [property: Category("Enable to Run:")]
        bool filter_Output;
        [ObservableProperty]
        private float botellas_hora;
        partial void OnBotellas_horaChanged(float value)
        {
            Botellas_segundo = value / 3600;
        }

        [ObservableProperty]
        private float botellas_segundo;
        partial void OnBotellas_segundoChanged(float value)
        {
            Botellas_hora = value * 3600;
        }

        [ObservableProperty]
        private float velocidad_actual_percentual;
        [ObservableProperty]
        private float diametro_botella;
        public override void UpdatePLC(PLCViewModel plc, int elapsedMilliseconds)
        {
            if (Consenso_NC)
                Consenso = !LeerBitTag(Tag_consenso);
            else
                Consenso = LeerBitTag(Tag_consenso);
        }

        private bool HayEspacioParaNuevaBotella(float X, float Y)
        {
            float radioMinimo = Diametro_botella / 4;  // Distancia mínima entre centros
            float radioMinimoCuadrado = radioMinimo * radioMinimo;

            // Buscar todas las botellas cercanas
            foreach (var obj in _mainViewModel.ObjetosSimulables)
            {
                if (obj is osBotella)
                {
                    float distanciaCuadrada = (float)(Math.Pow(obj.Left - X, 2) + Math.Pow(obj.Top - Y, 2));
                    if (distanciaCuadrada < radioMinimoCuadrado)
                    {
                        return false;  // Hay una botella demasiado cerca
                    }
                }
            }
            return true;  // No hay botellas cercanas
        }

        public override void UpdateControl(int elapsedMilliseconds)
        {
            bool habilitado;
            _TON_TOFF.Tiempo_ON_s = Filtro_consenso_ON_s;
            _TON_TOFF.Tiempo_OFF_s = Filtro_consenso_OFF_s;
            if (Consenso_Filtrado)
                habilitado = _TON_TOFF.SenalFiltrada();
            else
                habilitado = Consenso;
            Filter_Output = habilitado;

            if (habilitado && Velocidad_actual_percentual > 0)
            {
                if (PrimeraActualizacion)
                {
                    TiempoEntreBotellas = 3600 / (Botellas_hora * (Velocidad_actual_percentual / 100.0f));
                    TiempoRestante = TiempoEntreBotellas;
                    PrimeraActualizacion = false;
                }

                TiempoRestante -= elapsedMilliseconds / 1000.0f;
                if (TiempoRestante <= 0)
                {
                    var X = Left + OffsetLeftSalida;
                    var Y = Top + OffsetTopSalida;

                    if (HayEspacioParaNuevaBotella(X, Y))
                    {
                        var nuevaBotella = _mainViewModel.CrearObjetoSimulable(typeof(osBotella), X, Y);
                        ((osBotella)nuevaBotella).Diametro = Diametro_botella;
                        ((osBotella)nuevaBotella).Preserve_Outside_Transport = Preserve_Outside_Transport;
                        nuevaBotella.AutoCreated = true;

                        // Recalcular el tiempo entre botellas por si cambió la velocidad
                        TiempoEntreBotellas = 3600 / (Botellas_hora * (Velocidad_actual_percentual / 100.0f));
                        TiempoRestante = TiempoEntreBotellas;
                    }
                }
            }
            else
            {
                PrimeraActualizacion = true;
            }
        }

        public override void ucLoaded()
        {
            // El UserControl ya se ha cargado y podemos obtener las coordenadas para 
            // crear el objeto de simulacion
            base.ucLoaded();
        }

        private float TiempoEntreBotellas; // Nuevo: almacena el intervalo calculado
        private bool PrimeraActualizacion = true; // Nuevo: flag para la primera actualización
        public override void SimulationStop()
        {
            PrimeraActualizacion = true; // Reset del flag al detener
            base.SimulationStop();
        }
    }

    public partial class ucBottGenerator : UserControl, IDataContainer
    {
        public osBase? Datos { get; set; }
        public int zIndex_fromFrames { get; set; }

        public ucBottGenerator()
        {
            InitializeComponent();
            this.Loaded += OnLoaded;
            this.Unloaded += OnUnloaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Datos?.ucLoaded();
        }

        private void OnUnloaded(object sender, RoutedEventArgs e)
        {
            Datos?.ucUnLoaded();
        }

        public void Highlight(bool State)
        {
        }

        public ZIndexEnum ZIndex_Base()
        {
            return ZIndexEnum.Generadores;
        }
    }
}