using NIDAQmx.DAQmxEnum;
using NIDAQmxConst;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace NIDAQmx
{
    public class CI : BaseDevice
    {
        internal CI(DAQmxSession session, string deviceName) : base(session, deviceName)
        {
            PhysicalChans = GetPhysicalChans() ;
            CISupportedMeasTypes[] types = new CISupportedMeasTypes[Enum.GetValues<CISupportedMeasTypes>().Length];
            _Session.CheckResult(_Session.GetDelegate<Internal.Internal.DAQmxGetDevCISupportedMeasTypes>()(DeviceName, ref types[0], (uint)types.Length));
            SupportedMeasTypes = types.Where(x => (int)x > 0).ToArray();

            int val = 0;
            _Session.CheckResult(_Session.GetDelegate<Internal.Internal.DAQmxGetDevCITrigUsage>()(DeviceName, ref val));
            List<TriggerUsageTypeBits> bits = new List<TriggerUsageTypeBits>();
            Enum.GetValues<TriggerUsageTypeBits>().ToList().ForEach(x =>
            {
                if ((val & (int)x) == (int)x) bits.Add(x);
            });
            TrigUsage = bits.ToArray();
            Timing = new CITiming(session, deviceName);
            _Session.CheckResult(_Session.GetDelegate<Internal.Internal.DAQmxGetDevCIMaxSize>()(DeviceName, ref maxsize));
            _Session.CheckResult(_Session.GetDelegate<Internal.Internal.DAQmxGetDevCIMaxTimebase>()(DeviceName, ref maxtimebase));
        }
        private string[] GetPhysicalChans()
        {
            byte[] bytes = new byte[1024];
            _Session.CheckResult(_Session.GetDelegate<Internal.Internal.DAQmxGetDevCIPhysicalChans>()(DeviceName, ref bytes[0], (uint)bytes.Length));
            return System.Text.Encoding.UTF8.GetString(bytes).Trim('\0').Split(',').Select(x=>x.Trim('\0')).Where(x=>!string.IsNullOrEmpty(x)).ToArray();
        }
        private uint maxsize = 0;
        private double maxtimebase = 0;
        public string[] PhysicalChans { get; }
        public CISupportedMeasTypes[] SupportedMeasTypes { get; }
        public TriggerUsageTypeBits[] TrigUsage { get; }
        public uint MaxSize => maxsize;
        public double MaxTimebase => maxtimebase;
        public CITiming Timing { get; }

    }
}
