
using CtrEditor.Simulacion;
using CtrEditor.Siemens;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Diagnostics;


namespace CtrEditor.ObjetosSim
{
    /// <summary>
    /// Interaction logic for ucPhotocell.xaml
    /// </summary>
    public partial class osPhotocell : osBase, IosBase
    {
        private simBarrera Simulation_Photocell;
        Stopwatch timer;
        double timer_lastPositive;
        double timer_lastNegative;

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

        [ObservableProperty]
        Brush color;
        [ObservableProperty]
        bool luzCortada;

        partial void OnLuzCortadaChanged(bool value)
        {
            if (LuzCortada)
                Color = Brushes.Blue;
            else
                Color = Brushes.Green;
            if (Tipo_NC)
                EscribirBitTag(TagPhotocell_OUT, !LuzCortada);
            else
                EscribirBitTag(TagPhotocell_OUT, LuzCortada);
            if (Filter_Frecuency < 1)
            {
                Filter_Frecuency = 1;
                Frecuency = 0;
            }

            if (!value) {
                Lenght_positive_pulse = (float) (timer.ElapsedMilliseconds- timer_lastPositive);
                timer_lastNegative = timer.ElapsedMilliseconds;                
            } else
            {
                Lenght_negative_pulse = (float)(timer.ElapsedMilliseconds - timer_lastNegative);
                timer_lastPositive = timer.ElapsedMilliseconds;
                Lenght_FP_to_FP = Lenght_positive_pulse + Lenght_negative_pulse;
                Frecuency = (Frecuency * (filter_Frecuency - 1) + (1000 / Lenght_FP_to_FP)) / filter_Frecuency;
            }

        }

        [ObservableProperty]
        float distancia_cuello;

        [ObservableProperty]
        bool detectarCuello;

        partial void OnDetectarCuelloChanged(bool value)
        {
            if (Simulation_Photocell == null) return;

            Simulation_Photocell.DetectNeck = value;
        }


        [ObservableProperty]
        float filter_Frecuency;

        partial void OnFilter_FrecuencyChanged(float value)
        {
            if (value<=0)
                Filter_Frecuency = 10;
        }

        [ObservableProperty]
        float frecuency;

        [ObservableProperty]
        float lenght_positive_pulse;

        [ObservableProperty]
        float lenght_negative_pulse;

        [ObservableProperty]
        float lenght_FP_to_FP;

        [ObservableProperty]
        public bool tipo_NC;

        [ObservableProperty]
        public string tagPhotocell_OUT;


        public override void LeftChanged(float value)
        {
            ActualizarGeometrias();
        }

        public override void TopChanged(float value)
        {
            ActualizarGeometrias();
        }

        [ObservableProperty]
        public float ancho;

        partial void OnAnchoChanged(float value)
        {
            ActualizarGeometrias();
        }

        [ObservableProperty]
        public float alto;

        partial void OnAltoChanged(float value)
        {
            ActualizarGeometrias();
        }

        [ObservableProperty]
        public float angulo;

        partial void OnAnguloChanged(float value)
        {
            ActualizarGeometrias();
        }

        private void ActualizarGeometrias()
        {
            if (_visualRepresentation is ucPhotocell uc)
                UpdateRectangle(Simulation_Photocell, uc.Photocell, Alto, Ancho, Angulo);
        }

        public osPhotocell()
        {
            Ancho = 1;
            Alto = 0.03f;
            Frecuency = 0;
            timer = new Stopwatch();
            timer.Start();
        }

        public override void UpdateGeometryStart()
        {
            // Se llama antes de la simulacion
            ActualizarGeometrias();
        }
        public override void UpdateControl(int elapsedMilliseconds)
        {
            Distancia_cuello = Simulation_Photocell.Distancia;
            if (DetectarCuello)
                LuzCortada = Simulation_Photocell.LuzCortadaNeck;
            else
                LuzCortada = Simulation_Photocell.LuzCortada > 0;
        }
        public override void UpdatePLCPrimerCiclo()
        {
            // Escribimos el valor actual al iniciar la conexion
            // Esto es util para NC principalmente

            OnLuzCortadaChanged(LuzCortada);
        }
        public override void UpdatePLC(PLCModel plc, int elapsedMilliseconds) {
        }
        public override void ucLoaded()
        {
            // El UserControl ya se ha cargado y podemos obtener las coordenadas para 
            // crear el objeto de simulacion
            base.ucLoaded();

            if (_visualRepresentation is ucPhotocell uc)
                Simulation_Photocell = AddBarrera(simulationManager, uc.Photocell, Alto, Ancho, Angulo, DetectarCuello);
        }
        public override void ucUnLoaded()
        {
            // El UserControl se esta eliminando
            // eliminar el objeto de simulacion
            simulationManager.Remove(Simulation_Photocell);
        }


    }

    public partial class ucPhotocell : UserControl, IDataContainer
    {
        public osBase? Datos { get; set; }

        public ucPhotocell()
        {
            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 Resize(float width, float height)
        {
            if (width == 0) return;
            if (Datos is osPhotocell datos)
                datos.Ancho = PixelToMeter.Instance.calc.PixelsToMeters(width);
        }
        public void Move(float LeftPixels, float TopPixels)
        {
            if (Datos != null)
            {
                Datos.Left = PixelToMeter.Instance.calc.PixelsToMeters(LeftPixels);
                Datos.Top = PixelToMeter.Instance.calc.PixelsToMeters(TopPixels);
            }
        }
        public void Rotate(float Angle)
        {
            if (Datos != null)
                if (Datos is osPhotocell datos)
                    datos.Angulo = Angle;
        }
        public void Highlight(bool State) { }
        public int ZIndex()
        {
            return 16;
        }

    }
}
