
using CtrEditor.Simulacion;
using LibS7Adv;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Diagnostics;
using CtrEditor.FuncionesBase;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
using JsonIgnoreAttribute = Newtonsoft.Json.JsonIgnoreAttribute;
using System.ComponentModel;

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]        
        [property: Description("Color")]
        [property: Category("Layout:")]
        Brush color;

        [ObservableProperty]
        [property: Description("Light cut")]
        [property: Category("Debug:")]
        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.Elapsed.TotalMilliseconds - timer_lastPositive);
                timer_lastNegative = timer.Elapsed.TotalMilliseconds;                
            } else
            {
                Lenght_negative_pulse = (float)(timer.Elapsed.TotalMilliseconds - timer_lastNegative);
                timer_lastPositive = timer.Elapsed.TotalMilliseconds;
                Lenght_FP_to_FP = Lenght_positive_pulse + Lenght_negative_pulse;
                Frecuency = (Frecuency * (filter_Frecuency - 1) + (1000 / Lenght_FP_to_FP)) / filter_Frecuency;
            }

        }

        [ObservableProperty]
        [property: Description("Size of the Light.")]
        [property: Category("Setup:")]
        float ancho_Haz_De_Luz;

        [ObservableProperty]
        [property: Description("Distance to the neck.")]
        [property: Category("Debug:")]
        float distancia_cuello;

        [ObservableProperty]
        [property: Description("Type of detection: Neck of the bottle or Complete bottle.")]
        [property: Category("Setup:")]
        bool detectarCuello;

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

            Simulation_Photocell.DetectNeck = value;
        }


        [ObservableProperty]
        [property: Description("Filter signal.")]
        [property: Category("Setup:")]
        float filter_Frecuency;

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

        [ObservableProperty]
        [property: Category("Debug:")]
        float frecuency;

        [ObservableProperty]
        [property: Category("Debug:")]
        float lenght_positive_pulse;

        [ObservableProperty]
        [property: Category("Debug:")]
        float lenght_negative_pulse;

        [ObservableProperty]
        [property: Category("Debug:")]
        float lenght_FP_to_FP;

        [ObservableProperty]
        [property: Description("Type Filter signal.")]
        [property: Category("Setup:")]
        public bool tipo_NC;

        partial void OnTipo_NCChanged(bool value)
        {
            OnLuzCortadaChanged(LuzCortada);
        }

        [ObservableProperty]
        public string tagPhotocell_OUT;


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

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

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

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

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


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

        public osPhotocell()
        {
            Ancho = 1;
            Alto = 0.03f;
            Ancho_Haz_De_Luz = 0.01f;
            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(PLCViewModel 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 int zIndex_fromFrames { 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 Highlight(bool State) { }
        public ZIndexEnum ZIndex_Base()
        {
            return ZIndexEnum.Fotocelula;
        }


    }
}
