using NIDAQmx.DAQmxEnum;
using NIDAQmxConst;
using System.Runtime.CompilerServices;
using System.Text;

namespace NIDAQmx
{
    public class AI : BaseDevice
    {
        internal AI(DAQmxSession session, string deviceName) : base(session, deviceName)
        {
            PhysicalChans = GetPhysicalChans();
            SupportedMeasTypes = GetSupportedMeasTypes();
            Timing = new AITiming(session, deviceName);
            Trigger = new AITrigger(session, deviceName);
            Voltage = new AIVoltage(session, deviceName);
            Couplings = GetCouplings() ;
            LowpassCutoff = new AILowpassCutoff(session, deviceName);
        }
        private string[] GetPhysicalChans()
        {
            byte[] buffer = new byte[1024];
            _Session.CheckResult(_Session.GetDelegate<Internal.AI.DAQmxGetDevAIPhysicalChans>()(DeviceName, ref buffer[0], (uint)buffer.Length));
            return Encoding.UTF8.GetString(buffer).Trim('\0').Split(",").Select(x=>x.Trim('\0')).Where(x => !string.IsNullOrEmpty(x)).ToArray();
        }
        private AIMeasType[] GetSupportedMeasTypes()
        {

            AIMeasType[] types = new AIMeasType[Enum.GetValues<AIMeasType>().Length];
            _Session.CheckResult(_Session.GetDelegate<Internal.AI.DAQmxGetDevAISupportedMeasTypes>()(DeviceName, ref types[0], (uint)types.Length));
            return types.Where(x => x > 0).ToArray(); ;
        }
        private CouplingTypeBits[] GetCouplings()
        {
            int value =0;
            List<CouplingTypeBits> bits = new List<CouplingTypeBits>();
            _Session.CheckResult(_Session.GetDelegate<Internal.AI.DAQmxGetDevAICouplings>()(DeviceName, ref value));
            Enum.GetValues<CouplingTypeBits>().Select(x=>(int)x).ToList().ForEach(x =>
            {
                if( (x&value) ==x)
                {
                    bits.Add((CouplingTypeBits)x);
                }
            });
            return bits.ToArray(); ;
        }
        public string[] PhysicalChans { get; }
        public AIMeasType[] SupportedMeasTypes { get; }
        public AITiming Timing { get; }
        public AITrigger Trigger { get; }
        public AIVoltage Voltage { get; }
        public CouplingTypeBits[] Couplings { get; }
        public AILowpassCutoff LowpassCutoff { get; }
    }
}
