using System;
using Foundation;
using System.Runtime.InteropServices;

namespace AsReaderDock_VS
{
    public class PhyUtility
    {
        public static int PC_XI = 0x0200;
        public static int XPC_XEB = 0x8000;

        public PhyUtility()
        {
        }
        public static string GetEpcStringFromPcEPCData(NSData pcEpcData)
        {

            string tag = "";
            byte[] ptr = pcEpcData.ToArray();
            Marshal.Copy(pcEpcData.Bytes, ptr, 0, Convert.ToInt32(pcEpcData.Length));
            for (int i = 0; i < (int)pcEpcData.Length; i++) tag += (ptr[i] & 0xFF).ToString("X2");

            string strEpc = "";
            string pcEpc = tag;
            int pc = (int)(Utils.hexStringToLong(pcEpc.Substring(0, 4)));
            int result = pc & PC_XI;
            if (result != 0)
            {
                int xpc = (int)(Utils.hexStringToLong(pcEpc.Substring(4, 4)));
                int resultXPC = xpc & XPC_XEB;
                if (resultXPC != 0)
                {
                    strEpc = pcEpc.Substring(12, pcEpc.Length - 12);
                }
                else
                {
                    strEpc = pcEpc.Substring(8, pcEpc.Length - 8);
                }
            }
            else
            {
                strEpc = pcEpc.Substring(4, pcEpc.Length - 4);
            }
            return strEpc;
        }

        public static NSData hexStringToBytes(NSString stri)
        {
            string str = stri.ToString();
            if ((str.Length % 2) != 0)
                str = "0" + str;
            byte[] returnBytes = new byte[str.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
            return NSData.FromArray(returnBytes);
        }
        public static string toCharString(NSData data)
        {
            string str = "";
            byte[] ptr = data.ToArray();

            Marshal.Copy(data.Bytes, ptr, 0, Convert.ToInt32(data.Length));
            for (int i = 0; i < (int)data.Length; i++) str += (ptr[i]).ToString("c");
            return str;
        }
    }
}
