using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using iSTP_Embedded;

namespace iSTP_DataProcessing
{
    /// <summary>
    /// Provides filtration if it is required.
    /// </summary>
    public class Filtration
    {
        [DllImport("FilterButter1kHz.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        //public static extern unsafe IntPtr iSTP_ButterFilter_1000Hz(double[] data_in, double cutoffFreq_Hz);
        public static extern IntPtr iSTP_ButterFilter_1000Hz(double[] data_in, double cutoffFreq_Hz);

        #region --------------------------- Private global values ---------------------------
        private double CutoffFreq;
        static private object Locker = new object();
        #endregion

        #region --------------------------- Public global values ---------------------------
        #endregion

        #region --------------------------- Structures&Enums ---------------------------
        #endregion

        #region --------------------------- Construcotrs&Destructor ---------------------------
        /// <summary>
        /// Saves cut-off frequency
        /// </summary>
        /// <param name="cutoffFeq">Cut-off frequency</param>
        public Filtration(double cutoffFeq)
        {
            this.CutoffFreq = cutoffFeq;
        }
        #endregion

        #region --------------------------- Private sector ---------------------------
        #endregion

        #region --------------------------- Protected sector ---------------------------
        #endregion

        #region --------------------------- Public sector ---------------------------
        /// <summary>
        /// Applies filte on current datar
        /// </summary>
        /// <param name="incomePck">current data packet</param>
        public void CalcFiltration(ref EmbeddedPacket incomePck)
        {
            double[] data_in = new double[2000];
            double[] data_out = new double[2000];

            for (int i = 0; i < (incomePck.MsgLength / 4); i++)
            {
                data_in[i] = Convert.ToDouble(incomePck.GetData(i));
            }

            lock (Locker)
            {
                IntPtr ptr = iSTP_ButterFilter_1000Hz(data_in, CutoffFreq);
                Marshal.Copy(ptr, data_out, 0, 2000);
            }

            for (int i = 0; i < (incomePck.MsgLength / 4); i++)
            {
                incomePck.SetData(i, Convert.ToSingle(data_out[i]));
            }

            return;
        }
        #endregion
    }
}
