using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iq2dev.com.iqCommLib
{
    internal class GadgetInfo
    {
        public enum SupportedMode
        {
            Empty = 0x00,

            RS232 = 0x01,
            USB = 0x02,
            Ethernet = 0x04,
            Reserved3 = 0x08,

            Master = 0x10,
            Device = 0x20,
            Monitor = 0x40,
            TGA = 0x80,

            FD = 0x100,
            EMC = 0x200,
            Reserved11 = 0x400,
            Reserved12 = 0x800
        }

        public IQVersion HardwareRevision { get; private set; }

        public string SerialNummer { get; private set; }

        public UInt16 SoftwareVariant { get; private set; }

        public bool IsRS232Supported { get; private set; }
        public bool IsUsbSupported { get; private set; }
        public bool IsEthernetSupported { get; private set; }
        public bool IsMasterSupported { get; private set; }
        public bool IsGenericDeviceSupported { get; private set; }
        public bool IsMonitorSupported { get; private set; }
        public bool IsEmcSupported { get; private set; }


        public GadgetInfo(List<byte> bytes)
        {
            HardwareRevision = new IQVersion(bytes.GetRange(0, 2), 2);
            var serialNumberList = bytes.GetRange(2, 8);
            serialNumberList.Reverse();
            SerialNummer = Encoding.UTF8.GetString(serialNumberList.ToArray());

            var supportedModesMask = (UInt16)(bytes[10]);
            supportedModesMask |= (UInt16)((int)bytes[11] << 8);
            IsRS232Supported = IsOptionEnabled(SupportedMode.RS232, supportedModesMask);
            IsUsbSupported = IsOptionEnabled(SupportedMode.USB, supportedModesMask);
            IsEthernetSupported = IsOptionEnabled(SupportedMode.Ethernet, supportedModesMask);
            IsMasterSupported = IsOptionEnabled(SupportedMode.Master, supportedModesMask);
            IsGenericDeviceSupported = IsOptionEnabled(SupportedMode.Device, supportedModesMask);
            IsMonitorSupported = IsOptionEnabled(SupportedMode.Monitor, supportedModesMask);
            IsEmcSupported = IsOptionEnabled(SupportedMode.EMC, supportedModesMask);

            SoftwareVariant = BitConverter.ToUInt16(bytes.GetRange(12, 2).ToArray());
        }

        private bool IsOptionEnabled(SupportedMode mode, UInt16 mask)
        {
            return ((UInt16)mode & mask) == (UInt16)mode;
        }
    }
}
