using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNettyFrom.netty;

namespace DotNettyFrom.util
{
    public class AryUtil
    {
        public static string Bytes2Hex(byte[] bs)
        {
            return BitConverter.ToString(bs, 0, bs.Length).Replace("-", "").ToUpper();
        }


        public static byte[] Hex2Bytes(string hex)
        {
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
                hex += " ";
            byte[] returnBytes = new byte[hex.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hex.Substring(i * 2, 2).Trim(), 16);
            return returnBytes;
        }

        public static IByteBuffer Hex2IByteBuffer(string hex)
        {
            byte[] bytes = AryUtil.Hex2Bytes(hex);
            IByteBuffer msg = Unpooled.Buffer(bytes.Length);
            msg.WriteBytes(bytes);
            return msg;
        }

        public static string ByteBuffer2Hex(IByteBuffer msg)
        {
            byte[] byteBufferArray = new byte[msg.ReadableBytes];
            msg.ReadBytes(byteBufferArray);
            return AryUtil.Bytes2Hex(byteBufferArray);
        }
    }
}